gpt4 book ai didi

python - Matplotlib 条形图 - 类似于堆叠的叠加条

转载 作者:行者123 更新时间:2023-12-04 11:58:05 25 4
gpt4 key购买 nike

我想创建一个 matplotlib 条形图,它具有堆叠图的外观,而不是从多索引 Pandas 数据框中添加的。

下面的代码给出了基本的行为

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import io

data = io.StringIO('''Fruit,Color,Price
Apple,Red,1.5
Apple,Green,1.0
Pear,Red,2.5
Pear,Green,2.3
Lime,Green,0.5
Lime, Red, 3.0
''')
df_unindexed = pd.read_csv(data)
df_unindexed
df = df_unindexed.set_index(['Fruit', 'Color'])
df.unstack().plot(kind='bar')

绘图命令 df.unstack().plot(kind='bar')显示所有彼此相邻分组的苹果价格。如果您选择选项 df.unstack().plot(kind='bar',stacked=True) - 将红色和绿色的价格相加并叠加。

我想要一个介于两者之间的图 - 它将每个组显示为一个条形,但叠加了值,以便您可以看到所有值。下图(在 powerpoint 中完成)显示了我正在寻找的行为 -> 我想要右侧的图像。

没有计算所有值然后使用堆叠选项,这可能吗?

example bar plot

最佳答案

这(对我来说)似乎是一个坏主意,因为这种表示会导致几个问题。读者会明白那些不是放样的金条吗?当前面的杠比后面的高时会发生什么?

无论如何,为了完成你想要的,我只会重复拨打 plot()在数据的每个子集上并使用相同的轴,以便将条形绘制在彼此的顶部。
在您的示例中,“红色”价格总是较高,因此我必须调整顺序以将它们绘制在后面,否则它们会隐藏“绿色”条形。

fig,ax = plt.subplots()

my_groups = ['Red','Green']
df_group = df_unindexed.groupby("Color")

for color in my_groups:
temp_df = df_group.get_group(color)
temp_df.plot(kind='bar', ax=ax, x='Fruit', y='Price', color=color, label=color)

enter image description here

关于python - Matplotlib 条形图 - 类似于堆叠的叠加条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54036129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com