简体   繁体   English

如何在条形图中添加折线

[英]How to add a line to a bar chart

Diclaimer: I am still pretty new to data analysis and Python, so if you see a better way to write code for plotting my data, I would be more than happy to get feedback. 免责声明:我对数据分析和Python还是很陌生,因此,如果您看到一种更好的方法来编写用于绘制数据的代码,我将非常乐意获得反馈。

I have data for two different categories, over 7 weeks. 我有两个星期以上的两个不同类别的数据。 I need to plot this data onto a graph and make it easy to read. 我需要将此数据绘制到图形上并使其易于阅读。

The first thing I did it to create a bar chart with data from group 2 stacked on data from group 1. However I would also like to add a line to my graph that shows the evolution of the data from group 2 a little better. 我做的第一件事是创建一个条形图,其中将第2组的数据堆叠在第1组的数据上。但是,我也想在图形中添加一条线,以更好地显示第2组数据的演变。

But when I do so, the line seems to use different values for x, even though I used the exact same thing. 但是,当我这样做时,即使我使用的是完全相同的东西,该行似乎也为x使用了不同的值。

fig, ax = plt.subplots(figsize=(20,10))
sns.barplot('week', 'group1', data=memberships, color = '#E30613', saturation=1)
sns.barplot('week', 'group2', data=memberships, color = '#009FE3', bottom=group1, saturation=1)
sns.lineplot('week', 'group2', data=memberships)

The result 结果

What can I do to have the line on top of the bar chart? 我要怎么做才能在条形图上显示折线?

EDIT: To complement my question, here is the dataset I am using 编辑:为了补充我的问题, 是我正在使用的数据集

I struggled a lot with this one. 我为此付出了很多努力。 First I tried to plot using the plot methods from pandas but I could not manage to get the line graph on top of the bar graph. 首先,我尝试使用熊猫的plot方法进行plot ,但是我无法使线图位于条形图的顶部。 So I used the standard matplotlib functions. 因此,我使用了标准的matplotlib函数。

memberships = pd.DataFrame(data={'week':range(37,44), 
                                 'group1':[248, 243, 287, 354, 315, 348, 303], 
                                 'group2':[42,53,65,73,60,62,84]})

fig, ax = plt.subplots()
ax.bar(memberships.week-0.5, memberships.group1, color = '#E30613')
ax.bar(memberships.week-0.5, memberships.group2, color = '#009FE3', bottom=memberships.group1)
ax.plot(memberships.week, memberships.group2, linewidth=4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM