且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-28 12:15:41

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

There is no argument you can pass to df.plot that colorizes the bars differently for a single column.
Since bars for different columns are colorized differently, an option is to transpose the dataframe before plotting,

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

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

This would now draw the data as part of a subgroup. Therefore some tweaking needs to be applied to set the limits and xlabels correctly.

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 就足够了

While I guess this solution matches the criteria from the question, there is actually nothing wrong with using plt.bar. A single call to plt.bar is sufficient

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()