python - Matplotlib 堆积条形图:需要交换 x 和高度
问题描述
我正在查看一些世界生态足迹数据,我想为每种类型的足迹制作一个堆积条形图,其中堆积的值是相同的,但对于不同的国家。所以我开始使用其中的 2 个脚印,只是为了让某些东西发挥作用。
这就是我要做的(有点):
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Create DataFrame from CSV file
df = pd.read_csv('countries.csv')
# Slice Series out of DF
cropFoot = df['Cropland Footprint']
grazeFoot = df['Grazing Footprint']
# Convert Series to list
cropFoot = list(cropFoot)
grazeFoot = list(grazeFoot)
X = range(163) # the lists have 163 entries
plt.bar(X, height=cropFoot)
plt.bar(X, height=grazeFoot, bottom = cropFoot)
plt.show()
这会生成以下图:
我想在 x 轴上显示 5 个单独的足迹,以便每个国家/地区的足迹数据堆叠在一起。本质上,现在 x 轴显示了所有 163 个国家/地区,其中 2 个足迹堆叠在一起。我想要相反的。所以我想要 5 个条形图,每个条形图上堆放 163 个国家/地区。
像这样的东西(但堆叠了 163 件,而不是 7 件):
毫不奇怪,只是交换 X 和高度......不起作用。结果根本没有任何意义:
plt.bar(cropFoot, height=X)
plt.bar(grazeFoot, height=X, bottom = cropFoot)
plt.show()
看起来像这样:
关于如何正确扭转这种情况的任何建议?这是我正在使用的数据集,来自 Kaggle。
解决方案
由于您已经在使用数据框,您可能想尝试提供的条形图方法,该方法更易于使用。要堆叠,只需要设置参数stacked=True
。但是,堆叠的是列名,因此您必须先转置数据框。它可能看起来像这样:
footprints = ['Cropland Footprint', 'Grazing Footprint', ...] # fill with other footprints
data = df[footprints].T
data.plot.bar(stacked=True, legend=False) # you probably don't want a legend with 163 countries
举个例子:
df = pd.DataFrame(
np.arange(200).reshape(40, 5),
index=[f'i{x}' for x in range(40)],
columns=[f'c{x}' for x in range(5)]
)
df.T.plot.bar(stacked=True, legend=False)
推荐阅读
- reactjs - React Slick Sync - 功能组件
- gcc - ELF:为什么将struct变量放入64位系统中以32字节对齐的部分
- windows - Microsoft Store 应用程序未下载/更新应用程序 + Windows 更新未下载
- android - PlayStore:应用发布延迟超过 3 周
- xml - Tomcat 错误:prolog 中不允许有内容
- swift - 将 ONE 静态行添加到动态表
- phaser-framework - Detect collision direction in Phaser3
- r - 在R中将一个数组与另一个不同维度的数组相乘
- excel - 使用从工作簿中的选项卡创建的索引中的数据填充列分隔电子表格
- c# - 当异步函数被锁定时,会发生什么?钟