我正在寻找在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)
在RI中,可以使用以下一种格式创建我要查找的图表:
ggplot(survey, aes(x=seasons, fill=feelings)) + geom_bar(position = "fill")
看起来像这样:
如何以简单,紧凑的方式在python中创建此图表(最好使用matplotlib)?
我找到了一些(几乎)合适的解决方案,但它们都相当复杂,而且距离一线之隔还很遥远。还是在python(matplotlib)中不可能?
步骤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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句