Pandas DataFrame 条形图 - 从特定颜色图中绘制不同颜色的条形图 [英] Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap

查看:55
本文介绍了Pandas DataFrame 条形图 - 从特定颜色图中绘制不同颜色的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you plot the bars of a bar plot different colors only using the pandas dataframe plot method?

如果我有这个 DataFrame:

If I have this 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() 参数,以便图中的每个条形:

What df.plot() arguments do I need to set so each bar in the plot:

  1. 使用配对"颜色图
  2. 为每个条绘制不同的颜色

我正在尝试:

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

结果:

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

What I already know (yes, this works, but again, my purpose is to figure out how to do this with df.plot ONLY. Surely it must be possible?):

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 的参数来为单列以不同的方式着色条形.
由于不同列的条形颜色不同,一个选项是在绘图之前转置数据框,

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

这篇关于Pandas DataFrame 条形图 - 从特定颜色图中绘制不同颜色的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆