繁体   English   中英

Matplotlib堆叠条形图:需要交换x和高度

[英]Matplotlib stacked bar plot: need to swap x and height

我正在查看一些世界生态足迹数据,我想制作每种足迹类型的堆叠条形图,其中相互叠加的值是相同的,但适用于不同的国家。 因此,我开始使用其中的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个足迹。 我要相反。 因此,我希望每个条带上有163个国家/地区的5个条带。

像这样的东西(但有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)

在此处输入图片说明

我认为使用数据框条形图的@busybear答案会更好,但我想显示一个使用matplotlib.pyplot.bar的解决方案可能是适当的,因为这是问题的完整性。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Creates a randomized set of data to use for demonstration
n = 163
m = 5
footprints = np.zeros((m, n))
for ii in range(n):
    for jj in range(m):
        footprints[jj][ii] = random.random()*10

# This line is unnecessary for the example, it is purely for plot aesthetic
fig = plt.figure(figsize=(5, 5), dpi=200)

# colors can be replaced with any list of colors of any length >= 1
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
bottom = np.zeros(5)
for ii in range(1, n):
    for jj in range(m):
        plt.bar(jj, height=footprints[jj][ii], bottom=bottom[jj], 
                color=colors[ii % len(colors)])
        bottom[jj] = bottom[jj] + footprints[jj][ii]

plt.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM