首页 > 解决方案 > 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。

标签: pythonpython-3.xmatplotlibstacked-chart

解决方案


由于您已经在使用数据框,您可能想尝试提供的条形图方法,该方法更易于使用。要堆叠,只需要设置参数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)

在此处输入图像描述


推荐阅读