本文介绍了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')

现在这会将数据绘制为子组的一部分.因此,需要进行一些调整才能正确设置限制和xlabel.

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条形图-从特定颜色表绘制不同颜色的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:26