【问题标题】:Adjusting the color coding on a barplot so that all values are color coded correctly in matplotlib调整条形图上的颜色编码,以便在 matplotlib 中正确编码所有值
【发布时间】:2018-03-05 17:55:43
【问题描述】:

我有一个按州和类别(有 5 个类别)绘制比率的条形图,但问题是某些州的类别比其他州多。

import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({"state" : ["AL","AL","AL","AK", ],
                   "status" : ["Booked", "Rejected","Cancelled","Rejected"],
                   "0" : [1.5,2.5,3.5,1.0]})

df2 = df.groupby(['state','status']).size()/df.groupby(['state']).size()

fig, ax = plt.subplots()
plt.xlabel('State')
plt.ylabel('Bookings')

my_colors = 'gyr'
df2.plot(kind='bar', color=my_colors, orientation='vertical')

plt.tight_layout()
plt.show()

这很好地完成了我需要做的大部分工作,但是发生的情况是,由于某些州没有 status 的所有值,因此不会出现在图中,它会产生一些颜色编码不正确,因为颜色只是转移到每 5 种颜色重复一次,而不是基于值是否丢失。我该怎么办?

【问题讨论】:

标签: python python-3.x matplotlib plot bar-chart


【解决方案1】:

您可能希望以分组方式显示数据,即每组有 3 个类别,这样每个类别都有自己的颜色。

在这种情况下,这似乎可以通过取消堆叠多索引数据框轻松实现,

df2.unstack().plot(...)

完整示例:

import pandas as pd
import matplotlib.pyplot as plt


df = pd.DataFrame({"state" : ["AL","AL","AL","AK", ],
                   "status" : ["Booked", "Rejected","Cancelled","Rejected"],
                   "0" : [1.5,2.5,3.5,1.0]})

df2 = df.groupby(['state','status']).size()/df.groupby(['state']).size()

fig, ax = plt.subplots()
plt.xlabel('State')
plt.ylabel('Bookings')

my_colors = 'gyr'
df2.unstack().plot(kind='bar', color=my_colors, orientation='vertical', ax=ax)

plt.tight_layout()
plt.show()

【讨论】:

  • 非常感谢!我试图阅读关于堆叠/取消堆叠的内容,因为这在这里似乎是最关键的,并且不确定我是否完全遵循。从某种意义上说,这里的unstacking完成基本上有点像reverse reset_index,它基本上是按我的第二组按列分组,而不是按状态分组?
  • unstack 是某种旋转操作。它会根据您的状态列中的唯一项目创建尽可能多的列,即每个可能的状态都有自己的列。 Pandas 将以分组方式绘制不同的列,如图所示。
  • 对,但更具体地说,假设我会在我的数据框中按 5 个不同的列进行分组,然后取消堆叠将以何种方式对其进行分组/颜色编码?就像如果我在我的代码中使用 groupby State、City、Status、substatus 并使用 unstack,它将如何进行颜色编码?
  • 呃,我不知道 unstack 会在我的头顶超过 2 个级别的多索引上做什么。对于从这个答案以分组方式绘制,至少超过 2 个索引是没有意义的。
  • 既然 pandas 文档在这一点上并没有真正的帮助,为什么不尝试一下。无论如何,这是最好的学习方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2013-04-02
  • 2021-11-16
  • 1970-01-01
  • 2017-10-08
  • 2020-09-17
相关资源
最近更新 更多