如何在Python中绘制二进制彩色直方图?

时间:2016-05-26 16:41:26

标签: python matplotlib seaborn

我正在研究一个包含多个定量变量的二元分类项目。我想在探索性分析阶段绘制如下的直方图。然而,经过两天的在线研究,我仍然可以在Python中找到解决方案。

在R中,我知道如何使用单行代码:ggplot(train, aes(var_x, fill = var_y))。使用Python,任何人都可以告诉我matplotlib或seaborn的等效语法?

enter image description here

1 个答案:

答案 0 :(得分:-1)

要获得像seaborn中那样的重叠条形图,它比R中的一行代码稍微复杂一些。

你实际上需要创建两个图,一个用于'背景'一个用于前景'

stacked_bar_data["total"] = stacked_bar_data.Series1 + stacked_bar_data.Series2 # Creates 'total column of two series you're interested in.


#Plot 1 - background - "total" (top) series
sns.barplot(x = stacked_bar_data.Group, y = stacked_bar_data.total, color = "blue")

#Plot 2 - overlay - "bottom" series
bottom_plot = sns.barplot(x = stacked_bar_data.Group, y = stacked_bar_data.Series1, color = "red")


topbar = plt.Rectangle((0,0),1,1,fc="red", edgecolor = 'none')
bottombar = plt.Rectangle((0,0),1,1,fc='#0000A3',  edgecolor = 'none')
l = plt.legend([bottombar, topbar], ['Bottom Bar', 'Top Bar'], loc=1, ncol = 2, prop={'size':16})
l.draw_frame(False)

上述代码取自:http://randyzwitch.com/creating-stacked-bar-chart-seaborn/