python - 在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 行的作用是什么
f
?正如片段所代表的那样f
,它ax
代表什么? - 我无法使用添加轴标签和图表标题(如代码段的最后 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'
解决方案
希望下面的回答会有所帮助。
f
表示Figure
对象,它是所有绘图元素的顶级容器,并且ax
是对象或对象数组Axes
(在您的情况下是单个对象)您可以使用以下代码设置子图的标签和标题:
ax.set_xlabel('common xlabel') ax.set_ylabel('common ylabel') ax.set_title('ax title')
推荐阅读
- excel - 通过限制搜索电子邮件,其中主题包含非 ascii 字符(unicode #160)
- ios - 如何使用相同的模型对象在视图控制器之间传递模型数据
- php - php for 循环没有返回所有值,为什么?
- python - 从文件中查找字符串和字符串的索引到列表中
- ios - Firebase 数据库在模拟器和真实设备中没有响应
- dotnetnuke - 使用 aria-hidden="true" 将 DNN 页面分隔符包裹在 span 中?
- java - AuthenticationException:凭据无效!在 Hazelcast 中使用正确的凭据时
- python - 需要逗号的正则表达式,后跟空格,然后是州缩写
- uwp - UWP 应用无法再创建应用包
- keras - py_call_impl 中的错误(callable,dots$args,dots$keywords):ValueError:无法将字符串转换为浮点数:Null