Pandas DataFrame 条形图 - 从特定颜色图中绘制不同颜色的条形图

Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap

如何使用 pandas 数据框 plot 方法绘制不同颜色 的条形图?

如果我有这个 DataFrame:

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

   index  count
0      0   3372
1      1  68855
2      2  17948
3      3    708
4      4   9117

我需要设置哪些 df.plot() 个参数,以便图中的每个条形:

  1. 使用 'Paired' 颜色图
  2. 用不同的颜色绘制每个条形图

我正在尝试的是:

df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False)

结果:

我已经知道的(是的,这行得通,但同样,我的 目的 是弄清楚如何仅使用 df.plot 来做到这一点。当然它必须是可能吗?):

def f(df):
  groups = df.groupby('index')

  for name,group in groups:
    plt.bar(name, group['count'], label=name, align='center')

  plt.legend()
  plt.show()

您没有可以传递给 df.plot 的参数来对单个列的条形图进行不同的着色。
由于不同列的条形颜色不同,一个选项是在绘图之前转置数据框,

ax = df.T.plot(kind='bar', label='index', colormap='Paired')

这会将数据绘制为子组的一部分。因此,需要进行一些调整以正确设置限制和 xlabels。

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

ax = df.T.plot(kind='bar', label='index', colormap='Paired')
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()

虽然我猜这个解决方案符合问题的标准,但实际上使用 plt.bar 并没有错。一次调用 plt.bar 就足够了

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))

完整代码:

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

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))

plt.show()

您可以使用参数 color.

根据需要为每一列着色

例如(例如,有3个变量):

df.plot.bar(color=['C0', 'C1', 'C2'])

注:上面提到的字符串'C0', 'C1', ...'是matplotlib中内置的快捷颜色句柄。它们表示活动配色方案中的第一、第二、第三默认颜色,依此类推。事实上,它们只是一个示例,您可以使用 RGB 代码或任何其他颜色约定轻松使用任何自定义颜色。

您甚至可以突出显示特定的列,例如此处的中间列:

df.plot.bar(color=['C0', 'C1', 'C0'])

要在给出的示例代码中重现它,可以使用:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

ax = df.T.plot(kind='bar', label='index', color=['C0', 'C1', 'C2', 'C3', 'C4'])
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()

不同颜色的示例:

任意重复颜色的示例:

Link供参考:

在@Jairo Alves 工作中addition/extension你也可以指出具体的十六进制代码

df.plot(kind="bar",figsize=(20, 8),color=['#5cb85c','#5bc0de','#d9534f'])