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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44493417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:45:58  来源:igfitidea点击:

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

pythonpandasmatplotlibplot

提问by Jarad

How do you plot the bars of a bar plot different colors onlyusing the pandas dataframe plotmethod?

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

If I have this DataFrame:

如果我有这个 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

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

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

  1. Uses the 'Paired' colormap
  2. Plots each bar a different color
  1. 使用“配对”颜色图
  2. 为每个条绘制不同的颜色

What I am attempting:

我正在尝试什么:

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

The result:

结果:

not different colors

不是不同的颜色

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

我已经知道的(是的,这是可行的,但同样,我的目的是弄清楚如何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()

end result but used for loop

最终结果但用于循环

回答by ImportanceOfBeingErnest

There is no argument you can pass to df.plotthat 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,

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

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

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.

现在,这会将数据绘制为子组的一部分。因此,需要应用一些调整来正确设置限制和 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()

enter image description here

在此处输入图片说明

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.baris sufficient

虽然我猜这个解决方案符合问题的标准,但使用plt.bar. 一次调用plt.bar就足够了

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

enter image description here

在此处输入图片说明

Complete code:

完整代码:

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

回答by Jairo Alves

You can colorize each column as you like with the parameter color.

您可以根据需要使用参数为每一列着色color

For example (for example, with 3 variables):

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

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

Note: The strings 'C0', 'C1', ...'mentioned above are built-in shortcut color handles in matplotlib. They mean the first, second, third default colors in the active color scheme, and so on. In fact, they are just an example, you can use any custom color using the RGB code or any other color convention just as easily.

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

You can even highlight a specific column, for example, the middle one here:

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

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

To reproduce it in the example code given, one can use:

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

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

Example with different colors:

不同颜色的示例:

Example with different colors

不同颜色的例子

Example with arbitrary repetition of colors:

任意重复颜色的示例:

Example with arbitrary repetition of colors

任意重复颜色的示例

Link for reference: Assign line colors in pandas

参考链接:在Pandas中分配线条颜色