【问题标题】:How do I add a title to a grouped pandas dataframe?如何为分组的熊猫数据框添加标题?
【发布时间】:2018-01-08 01:11:11
【问题描述】:

我正在尝试更改由分组 pandas 数据框制作的直方图的标题、y 轴标题和 x 轴编号。这是我所说的一个例子:

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from random import randint
plt.style.use('seaborn-whitegrid')

a = []
for i in range(200):
    a.append(randint(0, 1))
b = []
for i in range(200):
    b.append(randint(1, 3))

d = {'A': a, 'B': b}
df = pd.DataFrame(data=d)

df_group = df.groupby(['A'], as_index = True)

df_group.hist(bins=5)

这是我在运行代码时看到的: Original Plot

我想做的是在python中编辑它看起来像这样(我在paint中做了这个): Edited Plot

任何帮助将不胜感激。

【问题讨论】:

  • df.groupby('A').plot.hist(bins=5, subplots=True, legend=True) 怎么样?
  • 没有。我得到了这个:PREFu.png

标签: python pandas group-by histogram


【解决方案1】:

这应该得到你想要的结果。

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from random import randint
plt.style.use('seaborn-whitegrid')

a = []
for i in range(200):
    a.append(randint(0, 1))
b = []
for i in range(200):
    b.append(randint(1, 3))

d = {'A': a, 'B': b}
df = pd.DataFrame(data=d)

df_group = df.groupby(['A'], as_index = True)

ax = df_group.hist(bins=5)
for i in range(len(ax)):
    ax[i][0][0].set_title(f"A-{i}")

我只是遍历子图并手动重命名它们。

【讨论】:

  • 这确实帮助了我的标题。谢谢你。但我仍然需要将 x 轴的数字更改为只有三个数字才能匹配相应的条形图。我也想给 y 轴一个标题。像这样:example
  • 通过使用 set_ylabel、set_xticks 和 set_xticklabels,并使用您用于上述标题的方法,我能够制作我想要的情节。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-06-16
  • 2020-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 2017-10-17
相关资源
最近更新 更多