python - Pandas:条形图,数据框中重复的 x 列中有两个条形图
问题描述
我有一个稍微奇怪的 csv 文件,其中月份列如此重复。我的目标是创建一个条形图,其中每个月都有两列 y(来自 a 和 b)。我试图通过将数据框分成两部分来解决这个问题 - 仅 a 和仅 b - 但是月份列的重复会妨碍。对 Python 和 Pandas 来说相当新,所以也许有一个我不知道的功能?任何帮助表示赞赏。
month cond. y
Jan a 4
Jan b 8
Feb a 2
Feb b 9
March a 3
March b 7
解决方案
解决此问题的最常见方法可能是将长格式数据通过pivot
然后重塑为宽格式DataFrame.plot
:
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame({
'month': ['Jan', 'Jan', 'Feb', 'Feb', 'March', 'March'],
'cond.': ['a', 'b', 'a', 'b', 'a', 'b'],
'y': [4, 8, 2, 9, 3, 7]
})
df.pivot(index='month', columns='cond.', values='y').plot(kind='bar', rot=0)
plt.tight_layout()
plt.show()
有一个明显的问题是 x 轴列出现乱序,因为它们是按字母顺序排列的,而不是按日期排序的。一种选择是reindex
在绘图之前。如果月份列是常规的,将会有更多选项,但由于它包含完整的月份名称和缩写,因此手动重新索引可能是最好的选择。
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame({
'month': ['Jan', 'Jan', 'Feb', 'Feb', 'March', 'March'],
'cond.': ['a', 'b', 'a', 'b', 'a', 'b'],
'y': [4, 8, 2, 9, 3, 7]
})
(
df.pivot(index='month', columns='cond.', values='y')
.reindex(['Jan', 'Feb', 'March']) # Re-order so they appear correctly on x-axis
.plot(kind='bar', rot=0)
)
plt.tight_layout()
plt.show()
Seaborn在解决这些类型的问题方面非常受欢迎,因为该hue
论点允许避免重塑步骤。此外x
将按照帧中出现的顺序,因此reindex
也是不必要的(假设数据在源 DataFrame 中以正确的顺序出现)
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
sns.set_theme() # (optional) Use seaborn theme
df = pd.DataFrame({
'month': ['Jan', 'Jan', 'Feb', 'Feb', 'March', 'March'],
'cond.': ['a', 'b', 'a', 'b', 'a', 'b'],
'y': [4, 8, 2, 9, 3, 7]
})
sns.barplot(data=df, x='month', y='y', hue='cond.')
plt.tight_layout()
plt.show()
推荐阅读
- java - java.lang.NoClassDefFoundError 加载英文类时
- oauth-2.0 - Open ID Connect 与移动客户端的最佳实践
- angular - 更新异步管道中使用的 observable 的一部分
- laravel - 如何从自定义 Laravel UserProvider 返回身份验证错误?
- ruby-on-rails - Rails:创建新记录时更新连接表自定义属性
- spring-boot - Ouath2 + jwt 和弹簧靴
- c# - 模糊匹配两个 csv 文件的最快方法
- jenkins - 如何解决 Jenkins 上的 Gruntfile.js“意外令牌”错误?
- binding - hyperjaxb 绑定自定义排除包
- python-3.x - Python - 安排关闭程序