首页 > 解决方案 > 使用带有 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 标签。

帮助?

标签: python-3.xpandasmatplotlib

解决方案


这是间接使用 x 和 y 标签作为文本的一种方法。我不知道使用plt.xlabelor的直接方式plt.ylabel。将轴对象传递给df.hist时,必须传入sharex和参数。在这里,您可以手动控制/指定要放置标签的位置。例如,如果您认为 x-label 太靠近刻度线,您可以使用将其稍微移到下方。shareyplt.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()

在此处输入图像描述


推荐阅读