【问题标题】:Giving x and y labels, titles and legends to individual histograms in python在 python 中为各个直方图提供 x 和 y 标签、标题和图例
【发布时间】:2021-05-21 20:03:54
【问题描述】:

我不熟悉在 Python 中使用直方图 我想通过从数据框中选择 11 列来显示 11 个直方图。 除了使用子图,我可以为每个直方图设置 xlabel、ylabel、图例和标题吗?

df.hist(column=['c1','c2','c3',.......'c11'], figsize=(20,20))

所有列都有不同的比例。 如果无法使用一个 hist() 来完成,我该如何使用 subplot 来完成?

【问题讨论】:

  • 请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?

标签: python pandas matplotlib histogram


【解决方案1】:

在这种情况下,df.hist() 返回一个二维坐标轴数组(每个坐标轴都指向一个子图)。您可以遍历这些轴并设置单独的 xlabels、ylabels、标题和图例。

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

df = pd.DataFrame({f'c{i}': np.random.randn(100) * i for i in range(1, 12)})
axes = df.hist(column=[f'c{i}' for i in range(1, 12)], figsize=(20, 20), label='histogram')
for i, ax in enumerate(axes.ravel(), start=1):
    if i <= 11:
        ax.set_xlabel(f'xlabel for column c{i}')
        ax.set_ylabel(f'ylabel for column c{i}')
        ax.set_title(f'title for column c{i}')
        ax.legend(title=f'legend for column c{i}')
plt.show()

【讨论】:

  • 使用 df.columns 代替 Column1 的标题如何直接添加列名而不是像 1,2 这样的索引?我试过这个:axes = white_wine_quality.hist(column=[f'{i}' for i in white_wine_quality.columns[i]], figsize=(20, 20), label='histogram') for i, ax in enumerate (axes.ravel(), start=1): if i
  • 请编辑您的原始问题并添加格式正确的附加代码。 cmets 不是用来添加代码的。
猜你喜欢
  • 2021-01-06
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
相关资源
最近更新 更多