首页 > 解决方案 > 在matplotlib中使用.subplot时如何添加标题、x轴标签和y轴标签?

问题描述

我有一个日期框架for_plot,我正在使用以下代码片段制作条形图:

import matlplotlib.pyplot as plt
f, ax = plt.subplots(1,1,figsize=(10,8))
x_1 = for_plot['res_code'] - 0.2
x_2 = for_plot['res_code']
pre = for_plot['n_indnota_pre']
post = for_plot['n_indnota_post']
ax.bar(x_1,pre, width = 0.2, color = 'red')
ax.bar(x_2,post, width = 0.2, color = 'green')
ax.set_xticks([0.9,1.9,2.9])
ax.set_xticklabels(['GEN','ST','SC'])
ax.legend(['pre_nota', 'post_nota'],loc = 1)

ax.xlabel('Constituency Type')
ax.ylabel('No of Independent Candidates')
ax.title('Average No Of Independent Candidates by Constituency Type')

plt.show()

我确实了解如何使用 matplotlib,但我对细微差别有一些疑问:

  1. 代码段第 1 行的作用是什么f?正如片段所代表的那样f,它ax代表什么?
  2. 我无法使用添加轴标签和图表标题(如代码段的最后 4 行),ax.xlabel('Constituency Type')但在绘制其他图形时,如果我不在subplot()第一行调用并使用plt.xlabel('Constituency Type'),它绝对可以正常工作。为什么它会这样?

我收到以下错误:

AttributeError: 'AxesSubplot' object has no attribute 'xlabel'

编辑1:

f.xlabel('Constituency Type')
f.ylabel('No of Independent Candidates')
f.title('Average No Of Independent Candidates by Constituency Type')

也不行。

AttributeError:'Figure' object has no attribute 'xlabel'

标签: pythonmatplotlibbar-chartdata-visualizationvisualization

解决方案


希望下面的回答会有所帮助。

  1. f表示Figure对象,它是所有绘图元素的顶级容器,并且ax是对象或对象数组Axes(在您的情况下是单个对象)

  2. 您可以使用以下代码设置子图的标签和标题: ax.set_xlabel('common xlabel') ax.set_ylabel('common ylabel') ax.set_title('ax title')


推荐阅读