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

zwghvu4y  于 2023-03-27  发布在  Python
关注(0)|答案(3)|浏览(149)

我正在寻找一个在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")

它看起来像这样:

我如何用Python(最好是用matplotlib)以一种简单而紧凑的方式创建这个图表?
我找到了一些(几乎)合适的解决方案,但它们都相当复杂,离一行程序还很远。或者这在python(matplotlib)中是不可能的?

xxb16uws

xxb16uws1#

**步骤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);

rsaldnfx

rsaldnfx2#

下面是一个使用seaborn的一行程序(基于matplotlib,可以通过matplotlib调用进一步定制)。

import pandas as pd
import seaborn as sns
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"]
    }
)
sns.histplot(df, x="seasons", hue="feelings", multiple="fill")

作为一个以前的R人,现在主要使用python,我也一直在寻找一种更简单的方法来做到这一点,而不依赖于plotnine,而是使用python社区更原生的绘图库。
希望这有帮助!

  • 使用的软件包:*
  • pandas==1.5.2
  • 海运==0.12.2
33qvvth1

33qvvth13#

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

输出如下:

相关问题