【问题标题】:Python (matplotlib) equivalent of stacked bar chart in R (ggplot)Python (matplotlib) 等效于 R (ggplot) 中的堆积条形图
【发布时间】:2021-01-16 22:45:29
【问题描述】:

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

虚拟数据(在 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")

看起来像这样:

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

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

【问题讨论】:

标签: python r matplotlib ggplot2


【解决方案1】:

如果你不喜欢 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')
)

输出如下:

【讨论】:

    【解决方案2】:

    第 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);
    

    【讨论】:

    • 非常感谢。那确实会创建相同的情节。但也许我在我的问题中没有说得足够清楚。在 matplotlib(或任何其他 python 包)中没有办法像在 R 中的 ggplot 中那样以简短而简单的方式(单线)创建类似的图?换句话说,是否真的有必要为这样的情节编写这么多代码,因此你会推荐使用 ggplot/R 而不是 python 来实现这样的目的吗?
    • 您需要准备数据和绘图。这是实现你想要的最短的方法。至少2行。 R 和 Python 不同。你应该选择适合你的东西
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多