5

我有一个数据框,对于每个索引,我必须绘制两个条形图(两个系列)。以下代码给出的输出为:

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

df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax = df.sort_values('B', ascending=True).plot.barh(rot=0,ax=ax,hatch="/")
plt.show()

在此处输入图像描述

我想为每个条分配单独的孵化。所以如果A有'/'孵化,B应该有'|'。我需要在代码中进行哪些修改?

4

3 回答 3

6

您可以分别绘制两个条形图:

import numpy as np
import pandas as pd

from matplotlib import pyplot as plt

df = pd.DataFrame(np.random.randint(0, 20, size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()

ax.barh(np.arange(0, len(df)), df['A'], height=0.3, hatch='/')
ax.barh(np.arange(0.3, len(df) + 0.3), df['B'], height=0.3, hatch='|')

在此处输入图像描述

于 2019-04-24T09:13:55.267 回答
4

matplotlib 文档提供了一个解决方案。但我不太喜欢它,因为它旨在为每个酒吧设置不同的舱口。

但恕我直言,在大多数情况下,为栏的每个“类别”设置一个特定的孵化更相关。您可以通过使用影线单独绘制条形图来做到这一点,也可以在绘制后设置影线。在绘图后设置阴影更加灵活,因此这是我的方法:

df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))
fig, ax = plt.subplots()
ax = df.sort_values('B', ascending=True).plot.barh(rot=0,ax=ax)
# get all bars in the plot
bars = ax.patches
patterns = ['/', '|']  # set hatch patterns in the correct order
hatches = []  # list for hatches in the order of the bars
for h in patterns:  # loop over patterns to create bar-ordered hatches
    for i in range(int(len(bars) / len(patterns))):
        hatches.append(h)
for bar, hatch in zip(bars, hatches):  # loop over bars and hatches to set hatches in correct order
    bar.set_hatch(hatch)
# generate legend. this is important to set explicitly, otherwise no hatches will be shown!
ax.legend()
plt.show()

与单独绘制条形图相比,此解决方案的优点是:

  • 你可以有任意数量的酒吧
  • 适用于所有可能组合的堆叠和/或非堆叠条
  • 与熊猫绘图界面一起使用

主要缺点是额外的 LOC,特别是对于仅绘制几个条形图。但是将它打包成一个函数/模块并重新使用它可以解决这个问题。:)

于 2019-04-24T09:17:02.993 回答
1

这是一个测试 ca 可以帮助你

import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.randint(0,20,size=(5, 2)), columns=list('AB'))

plt.hist(df['A'], color = 'blue',
            edgecolor = 'red', hatch = '/' , label = 'df.A',orientation = 'horizontal',
            histtype = 'bar')
plt.hist(df['B'],color = 'YELLOW',
            edgecolor = 'GREEN', hatch = 'O' , label = 'df.B',orientation = 'horizontal',
            histtype = 'bar')
plt.legend()
plt.show()
于 2019-04-24T09:51:27.523 回答