如何用直方图p显示Pandas分组中的标签名称

2024-04-25 06:37:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用熊猫在一个图中绘制多个柱状图,但缺少一些东西:

  1. 如何给标签。在
  2. 我只能绘制一个图形,如何将其更改为layout=(3,1)或其他图形。在
  3. 另外,在图1中,所有的箱子都是用纯色填充的,很难知道哪一个是哪个,如何填充不同的标记(例如十字、斜杠等)?在

以下是MWE:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

df = sns.load_dataset('iris')

df.groupby('species')['sepal_length'].hist(alpha=0.7,label='species')
plt.legend()

输出: enter image description here

要改变布局,我可以用关键字,但不能给他们颜色

如何给不同的颜色?在

^{pr2}$

给出: enter image description here


Tags: 标记import图形df颜色as绘制plt
2条回答

您可以解析为groupby

fig,ax = plt.subplots()

hatches = ('\\', '//', '..')         # fill pattern
for (i, d),hatch in zip(df.groupby('species'), hatches):
    d['sepal_length'].hist(alpha=0.7, ax=ax, label=i, hatch=hatch)

ax.legend()

输出:

enter image description here

这是更多的代码,但是使用纯matplotlib总是可以让您更好地控制绘图。第二个案子:

import matplotlib.pyplot as plt
import numpy as np
from itertools import zip_longest

# Dictionary of color for each species
color_d = dict(zip_longest(df.species.unique(), 
                           plt.rcParams['axes.prop_cycle'].by_key()['color']))

# Use the same bins for each
xmin = df.sepal_length.min()
xmax = df.sepal_length.max()
bins = np.linspace(xmin, xmax, 20)

# Set up correct number of subplots, space them out. 
fig, ax = plt.subplots(nrows=df.species.nunique(), figsize=(4,8))
plt.subplots_adjust(hspace=0.4)

for i, (lab, gp) in enumerate(df.groupby('species')):
    ax[i].hist(gp.sepal_length, ec='k', bins=bins, color=color_d[lab])
    ax[i].set_title(lab)

    # same xlim for each so we can see differences
    ax[i].set_xlim(xmin, xmax)

enter image description here

相关问题 更多 >