Matplotlib 不会为高度为 0 的条形分配颜色

Matplotlib does not assign color to bar with height 0

提问人:Paulo Sigiani 提问时间:11/10/2023 最后编辑:CorralienPaulo Sigiani 更新时间:11/10/2023 访问量:58

问:

我想将绘图中条形的颜色更改为:

  • 1990-1999: 红色
  • 2000-2009: 蓝色
  • 2010 - 2022: 绿色

但是 Matplotlib 不会为高度为 0 的条形分配颜色。

然后我用这种颜色创建了一个列表:

colors = ['red' if 1990 <= year <= 1999 else 'blue' if 2000 <= year <= 2009 else 'green' for year in range(1999, 2023)]

然后我设置参数:plt.bar

plt.bar(table['Year'], table['Occurrences'], color = colors)

但是当某个条形的值为 0 时,不会分配颜色:

所有高度均为正的示例:

enter image description here

高度为 0 的示例:

enter image description here

您可以看到,当条形有高度时,代码有效,但是在第二个图中,没有为0的条形分配颜色,因此将相应的颜色分配给下一个具有正高度的条形。如何使 Matplotlib 尊重颜色的位置?

python pandas matplotlib jupyter-notebook

评论


答:

0赞 Panda Kim 11/10/2023 #1

示例代码

我们需要最小且可重复的例子来解决问题

import pandas as pd
df = pd.DataFrame({'year':[1990, 1999, 2002, 2021], 'value':[30, 0, 15, 20]})

DF:

    year    value
0   1990    30
1   1999    0
2   2002    15
3   2021    20

法典

使用年份列制作颜色图

import numpy as np
cond1 = df['year'].between(1990, 1999)
cond2 = df['year'].between(2000, 2009)
colormap = np.select([cond1, cond2], ['red', 'blue'], 'green')

颜色图:

array(['red', 'red', 'blue', 'green'], dtype='<U5')

使用colormap

df.plot(kind='bar', x='year', y='value', color=colormap, legend=False)

enter image description here

1990-1999: 红色, 2000 - 2009: 蓝色, 2010 - 2022: 绿色

0赞 Corralien 11/10/2023 #2

您的问题无论是使用还是使用都无法重现matplotlibpandas

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(2023)
table = pd.DataFrame({'Year': np.arange(1990, 2023),
                      'Occurrences': np.random.choice([10, 20, 30, 0], 33)})
colors = ['red' if 1990 <= year <= 1999
          else 'blue' if 2000 <= year <= 2009
          else 'green' for year in range(1990, 2023)]

输出方式:pandas

>>> table.plot.bar(x='Year', y='Occurrences', color=colors, legend=False)

enter image description here

输出方式:matplotlib

>>> plt.bar(table['Year'], table['Occurrences'], color=colors)

enter image description here

但是,如果您缺少年份,颜色似乎被“转移”了:table

# remove 1993, 2000 is now red (and not blue), 2010 is now blue (and not green)
>>> plt.bar(table['Year'].drop(3), table['Occurrences'].drop(3), color=colors)

enter image description here

我认为你的表格中缺少一年。尝试:

>>> set(np.arange(1990, 2023)).difference(table['Year'])  # I removed 1993 here
{1993}  # <- missing year(s)

要获得包含所有年份的完整表格,请执行以下操作:

table = table.set_index('Year').reindex(np.arange(1990, 2023), fill_value=0).reset_index()

现在您可以绘制图表了。