在 matplotlib 中使用 .subplot 时如何添加标题、x 轴标签和 y 轴标签?
How to add title, x axis label and y axis label while using .subplot in matplotlib?
我有一个名为 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 行中的
f
有什么作用?正如代码片段所示,f
和 ax
代表什么?
- 我无法使用
ax.xlabel('Constituency Type')
添加坐标轴标签和图表标题(如代码片段的最后 4 行),但在绘制其他图形时,如果我不调用 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'
希望以下回答对您有所帮助。
f
表示 Figure
object 是所有绘图元素的顶级容器,而 ax
是 object 或Axes
objects 数组(在你的例子中是单个 object)
您可以使用下面的代码来设置子图的标签和标题:
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')
ax.set_title('ax title')
我有一个名为 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 行中的
f
有什么作用?正如代码片段所示,f
和ax
代表什么? - 我无法使用
ax.xlabel('Constituency Type')
添加坐标轴标签和图表标题(如代码片段的最后 4 行),但在绘制其他图形时,如果我不调用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'
希望以下回答对您有所帮助。
f
表示Figure
object 是所有绘图元素的顶级容器,而ax
是 object 或Axes
objects 数组(在你的例子中是单个 object)您可以使用下面的代码来设置子图的标签和标题:
ax.set_xlabel('common xlabel') ax.set_ylabel('common ylabel') ax.set_title('ax title')