简体   繁体   English

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

[英]Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap

How do you plot the bars of a bar plot different colors only using the pandas dataframe plot method?如何使用熊猫数据框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为每个条绘制不同的颜色

What I am attempting:我正在尝试什么:

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

The result:结果:

不是不同的颜色

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?):我已经知道的(是的,这是可行的,但同样,我的目的是弄清楚如何仅使用df.plot来做到这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()

最终结果但用于循环

There is no argument you can pass to df.plot that colorizes the bars differently for a single column.没有任何参数可以传递给df.plot以不同方式为单列着色条形。
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')

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

在此处输入图片说明

While I guess this solution matches the criteria from the question, there is actually nothing wrong with using plt.bar .虽然我猜这个解决方案符合问题的标准,但使用plt.bar实际上没有任何问题。 A single call to plt.bar is sufficient一次调用plt.bar就足够了

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

在此处输入图片说明

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

You can colorize each column as you like with the parameter color .您可以根据需要使用参数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.注意:上面提到的字符串'C0', 'C1', ...'是 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.事实上,它们只是一个示例,您可以使用 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 arbitrary repetition of colors:任意重复颜色的示例:

任意重复颜色的示例

Link for reference: Assign line colors in pandas参考链接: 在熊猫中分配线条颜色

In addition/extension to @Jairo Alves work you can also indicate the specific hex code除了/扩展@Jairo Alves 工作,您还可以指明特定的十六进制代码

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 熊猫Matplot检索颜色图堆叠条形图使用的颜色 - pandas matplot retrieve colors used by colormap stacked bar plot how to remove empty space from bars for a specific group, that was plotted as seaborn bar plot on data in pandas dataframe - how to remove empty space from bars for a specific group, that was plotted as seaborn bar plot on data in pandas dataframe 如何在带有误差线的条形图中绘制熊猫数据框的特定行和列(基于行名和列名)? - How to plot specific rows and columns of pandas dataframe (based on name of row and name of column) in bar plot with error bars? 具有特定颜色和图例位置的熊猫条形图? - Pandas bar plot with specific colors and legend location? 在groupby图中从颜色图中排除特定颜色 - Exclude specific color/colors from colormap in groupby plot 熊猫情节酒吧不同颜色不按预期工作 - Pandas plot bar with different colors not working as expected Pandas 中不同颜色的堆积条形图 - Stacked bar plot in different colors in Pandas 将 pandas 数据框绘制为具有不同颜色的直方图 - Plot pandas dataframe as histogram with different colors 有条件地分割熊猫数据框以使用不同的颜色进行绘制 - Split pandas dataframe conditionally to plot with different colors 将熊猫数据框中的图中的堆叠条形图分组 - Grouped stacked bars in a plot from pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM