Python(matplotlib)等效于R(ggplot)中的堆叠条形图

2024-10-04 07:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找在python(matplotlib)中使用R(ggplot)创建的以下堆叠条形图的等效项:

虚拟数据(在R中)如下所示:

seasons <- c("Winter", "Winter", "Winter", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Fall", "Fall", "Fall")
feelings <- c("Cold", "Cold", "Cold", "Warm", "Warm", "Cold", "Warm", "Warm", "Warm", "Warm", "Cold", "Cold")
survey <- data.frame(seasons, feelings)

在R中,我可以使用以下一行创建我要查找的图表:

ggplot(survey, aes(x=seasons, fill=feelings)) + geom_bar(position = "fill")

看起来是这样的:

stacked bar chart

如何用python(最好使用matplotlib)以简单紧凑的方式创建此图表

我找到了一些(几乎)合适的解决方案,但它们都相当复杂,而且远离一条直线。或者这在python(matplotlib)中是不可能的


Tags: 数据matplotlib图表fillsurvey条形图summerspring
2条回答

如果您不喜欢matplotlib,并且确实喜欢ggplot,那么您可以使用plotnine库,它是Python中ggplot的克隆。语法几乎相同:

import pandas as pd
from plotnine import *

survey = pd.DataFrame({
    'seasons': ['Winter', 'Winter', 'Winter', 'Spring', 'Spring', 'Spring', 'Summer', 'Summer', 'Summer', 'Fall', 'Fall', 'Fall'],
    'feelings': ['Cold', 'Cold', 'Cold', 'Warm', 'Warm', 'Cold', 'Warm', 'Warm', 'Warm', 'Warm', 'Cold', 'Cold'],
})

(
    ggplot(survey, aes(x='seasons', fill='feelings'))
    + geom_bar(position = 'fill')
)

结果如下:

enter image description here

第1步。准备数据

df = pd.DataFrame(
    {
        "seasons":["Winter", "Winter", "Winter", "Spring", "Spring", "Spring", "Summer", "Summer", "Summer", "Fall", "Fall", "Fall"],
        "feelings":["Cold", "Cold", "Cold", "Warm", "Warm", "Cold", "Warm", "Warm", "Warm", "Warm", "Cold", "Cold"]
    }
)


df_new = df.pivot_table(columns="seasons", index="feelings", aggfunc=len, fill_value=0).T.apply(lambda x: x/sum(x), axis=1)
df_new
feelings      Cold      Warm
seasons                     
Fall      0.666667  0.333333
Spring    0.333333  0.666667
Summer    0.000000  1.000000
Winter    1.000000  0.000000

第2步。绘制数据

ax = df_new.plot.bar(stacked=True)
ax.set_xticklabels(ax.get_xticklabels(), rotation=0)
plt.style.use('ggplot')
plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5), title="feelings", framealpha=0);

enter image description here

相关问题 更多 >