来自pandas dataframe python的barh图表中行的不同颜色

mic*_*mir 4 python matplotlib bar-chart pandas

我有以下pandas数据帧:

              a   b
    bob      23  25
    john     13  21
    paul     20  19
    david    17  14
    michael  14  24
    neil     22  11 

    df.plot(kind='barh')
Run Code Online (Sandbox Code Playgroud)

我使用了熊猫情节功能.我想制作一个带有不同颜色的所有行(名称)的条形图有没有办法做到这一点?

在此输入图像描述 我需要所有人都有不同颜色的酒吧.

and*_*rew 5

看起来Pandas仅支持使用colormap属性,该属性将相同的地图应用于图表中的每一行,例如:

df.plot(kind='barh', colormap='RdBu')
Run Code Online (Sandbox Code Playgroud)

出于您的目的,您需要直接使用Matplotlib.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'a':[23, 13, 20, 17, 14, 22],
                   'b':[25, 21, 19, 14, 23, 11]},
                   index=['bob', 'john', 'paul', 'david', 'michael', 'neil'])

a_vals = df.a
b_vals = df.b
ind = np.arange(df.shape[0])
width = 0.35

# Set the colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'g']


def autolabel(bars):
    # attach some text labels
    for bar in bars:
        width = bar.get_width()
        ax.text(width*0.95, bar.get_y() + bar.get_height()/2,
                '%d' % int(width),
                ha='right', va='center')

# make the plots
fig, ax = plt.subplots()
a = ax.barh(ind, a_vals, width, color = colors) # plot a vals
b = ax.barh(ind + width, b_vals, width, color = colors, alpha=0.5)  # plot b vals
ax.set_yticks(ind + width)  # position axis ticks
ax.set_yticklabels(df.index)  # set them to the names
ax.legend((a[0], b[0]), ['a', 'b'], loc='center right')

autolabel(a)
autolabel(b)

plt.show()
Run Code Online (Sandbox Code Playgroud)

请参考以下示例:

1 - matplotlib条形图

2- 在条形图上更改单个颜色

在此输入图像描述