[英]Plot a barplot AND lineplot with multiple columns in seaborn
I'm trying to plot a barplot for a dataframe with multiple columns using seaborn, while on the 2nd y-axis I plot a lineplot for a dataframe with multiple columns.我正在尝试使用 seaborn 为 plot 绘制多列 dataframe 的条形图,而在第二个 y 轴上,我 plot 绘制多列 dataframe 的线图。 The barplot is working well, but when I also plot the lineplot the entire x-axis shifts.. How can I solve this?
barplot 运行良好,但是当我也 plot lineplot 整个 x 轴移动时。我该如何解决这个问题?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Loss dataframe
dfL = pd.DataFrame({"date": [2015, 2016, 2017, 2018, 2019, 2020, 2021],
"region1": [3, 2, 5, 2, 4, 2, 4],
"region2": [5, 2, 3, 2, 1, 2, 1]})
dfLstack = dfL.set_index('date').stack().reset_index()
dfLstack.columns = ['year', 'district', 'loss']
# Total before 2015
region1_2015 = 70
region2_2015 = 50
# Total dataframe: total before 2015 minus annual loss
dfT = pd.DataFrame({"date": [2015, 2016, 2017, 2018, 2019, 2020, 2021],
"region1": [67, 65, 60, 58, 54, 52, 48],
"region2": [45, 43, 40, 38, 37, 35, 34]})
dfTstack = dfT.set_index('date').stack().reset_index()
dfTstack.columns = ['year', 'district', 'total']
ax = sns.barplot(y = 'loss', x = 'year', hue = 'district', data = dfLstack, palette = 'pastel')
ax2 = plt.twinx()
# Lines below produce a figure that is incorrect
sns.lineplot(y = 'total', x = 'year', hue = 'district', data = dfTstack, palette = 'pastel', ax=ax2, legend = False)
ax.figure.legend()
plt.show()
# How to plot both a barplot and lineplot in the same figure?
This is due to the fact that the barplot uses [0, 1, 2...] as x values, even if there are labels with 2015, 2016, 2017... while the lineplot uses 2015, 2016, 2017...这是因为条形图使用 [0, 1, 2...] 作为 x 值,即使有带有 2015、2016、2017... 的标签,而线图使用 2015、2016、2017...
To correct this, you can avoid using ax.twinx
and overlay 2 graphs instead:要更正此问题,您可以避免使用
ax.twinx
并改为覆盖 2 个图形:
# plot first graph
ax = sns.barplot(y='loss', x='year', hue='district',
data=dfLstack, palette='pastel')
# create second independent axes overlayed on the first
# is is important to use a different label
ax2 = ax.figure.add_subplot(111, label='line')
# plot second graph
sns.lineplot(y='total', x='year', hue='district', data=dfTstack,
palette='pastel', ax=ax2, legend=False)
# align the x-axis, remove the background, (re)move the ticks
# barplot has a xlim from -0.5 to n+0.5
ax2.set_xlim(dfT['date'].min()-0.5, dfT['date'].max()+0.5)
# remove white background
ax2.set_facecolor('None')
# remove duplicated x-axis (check first that it is properly aligned)
ax2.xaxis.set_visible(False)
# move the y-ticks to the right
ax2.yaxis.tick_right()
output: output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.