python-3.x - 使用带有 by 参数的 pandas hist() 函数显示多个直方图时,如何显示 x 和 y 标签?
问题描述
我正在尝试创建一系列共享 x 和 y 标签的图表。我可以让每个图表都有一个标签(在这里解释得很好!),但这不是我想要的。
我想要一个涵盖两个图的 y 轴的标签,并且与 x 轴相同。
我一直在查看 matplotlib 和 pandas 文档,但在 usingby
参数时找不到任何解决此问题的方法。
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'A': [1, 2, 1, 2, 3, 4, 3, 4],
'B': [1, 7, 2, 4, 1, 4, 8, 3],
'C': [1, 4, 8, 3, 1, 7, 3, 4],
'D': [1, 2, 6, 5, 8, 3, 1, 7]},
index=[0, 1, 2, 3, 5, 6, 7, 8])
histo = df.hist(by=df['A'], sharey=True, sharex=True)
plt.ylabel('ylabel') # I assume the label is created on the 4th graph and then deleted?
plt.xlabel('xlabel') # Creates a label on the 4th graph.
plt.tight_layout()
plt.show()
输出看起来像这样。
有什么方法可以创建一个横跨图像整个左侧的 Y 标签(不是单独的每个图形),对于 X 标签也是如此。
如您所见,x 标签只出现在最后创建的图形上,没有 y 标签。
帮助?
解决方案
这是间接使用 x 和 y 标签作为文本的一种方法。我不知道使用plt.xlabel
or的直接方式plt.ylabel
。将轴对象传递给df.hist
时,必须传入sharex
和参数。在这里,您可以手动控制/指定要放置标签的位置。例如,如果您认为 x-label 太靠近刻度线,您可以使用将其稍微移到下方。sharey
plt.subplots()
0.5, -0.02, 'X-label'
import matplotlib.pyplot as plt
import pandas as pd
f, ax = plt.subplots(2, 2, figsize=(8, 6), sharex=True, sharey=True)
df = pd.DataFrame({'A': [1, 2, 1, 2, 3, 4, 3, 4],
'B': [1, 7, 2, 4, 1, 4, 8, 3],
'C': [1, 4, 8, 3, 1, 7, 3, 4],
'D': [1, 2, 6, 5, 8, 3, 1, 7]},
index=[0, 1, 2, 3, 5, 6, 7, 8])
histo = df.hist(by=df['A'], ax=ax)
f.text(0, 0.5, 'Y-label', ha='center', va='center', fontsize=20, rotation='vertical')
f.text(0.5, 0, 'X-label', ha='center', va='center', fontsize=20)
plt.tight_layout()
推荐阅读
- python - Django:如何在不重新加载页面的情况下提交表单并在同一页面上接收结果
- unity3d - 如何更改对象的中心以正确旋转?
- vb.net - 使两个组合框的输入从 csv 文件中搜索、读取和显示数据
- css - 更改传入字符串中特定单词的颜色
- algorithm - 从城市 1 到达城市 N 的最短时间
- r - 使用循环将矩阵转换为另一个矩阵
- asp.net-mvc - 在从 Swagger 2.0 到 3.0 的 swagger 更改中将整数列表发送到 API 端点
- excel - Excel:自动化 COUNTIF(基于另一个表)
- android - 如何在 request.newBuilder() 中调用 httpLoggingInterceptor
- javascript - URL.format 不是函数