【问题标题】:Color problems with pandas matplotlib - graph colors are inconsistentpandas matplotlib 的颜色问题 - 图形颜色不一致
【发布时间】:2019-02-27 00:18:58
【问题描述】:

我的图表只有 3 种颜色 - 值 A、B、C 的绿色、红色、灰色。该应用程序使用分组依据和值计数来获取 A、B 和 C 跨月的累积计数,并显示一个甜甜圈图表、barh 和条形图。颜色从一个图转移到另一个图 - 在一个图上,A 是绿色,而另一个具有相同数据的图将 A 显示为红色。

简单的修复,对吧?

def color_for_label(label):
    xlate = {'A': 'green',
             'B': 'red',
             'C': 'grey',
             }
    return [xlate[x] for x in label]


chart = gb.unstack(level=-1)
               .plot.barh(color=color_for_label(gb.index[0:2].names), 
                width=.50,
                stacked=True, 
                legend=None)  

数据有时返回一个索引,有时返回一个多索引。它会窒息,但可以正常工作

颜色是恒定的红色/绿色/灰色,始终与值 A/B/C 一致。

我尝试过检查数据类型和 try/except 结构,但都很快变得过于复杂。谁有一个简单的解决方案可以分享?

让我们使用此示例中的数据pandas pivot table to stacked bar chart

df.assign(count =1 ).groupby(['battle_type']).count().plot.barh(stacked=True)

和(后者首选 - 我不喜欢 groupby 不一致)

df.pivot_table(index='battle_type', columns='attacker_outcome', aggfunc='size').plot.barh(stacked=True)

两个都得到我

在上面的 A、B、C 示例中,我有第三个值“Tie”,但我们暂时忽略它。

我想确保胜利总是绿色,失败是红色,平局是灰色。

所以我有我的简单功能

def color_for_label(label):
    xlate = {'win': 'green',
             'lose': 'red',
             'Tie': 'grey',
             }
return xlate[label]

所以我添加

....plot.barh(stacked=True, color=color_for_label(**label**))

我在这里卡住了 - 我应该将标签设置为什么,以便胜利总是绿色,失败是红色,领带是灰色?

【问题讨论】:

标签: pandas matplotlib


【解决方案1】:

知道了!

首先,为新示例翻译颜色

def color_for_label(label):
    xlate = {'win': 'green',
             'loss': 'red',
             'tie': 'grey',
             }
    return [xlate[x] for x in label]

然后把它分成两行。

# create a dataframe
gb = df.pivot_table(index='battle_type', columns='attacker_outcome', aggfunc='size')

# pass the dataframe column values
gb.plot.barh(stacked=True, color=color_for_label(gb.columns.values))

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-06-11
  • 2018-01-22
  • 1970-01-01
  • 2020-10-07
  • 1970-01-01
  • 2013-12-24
  • 2018-03-23
  • 1970-01-01
相关资源
最近更新 更多