简体   繁体   中英

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. The barplot is working well, but when I also plot the lineplot the entire x-axis shifts.. How can I solve this?

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...

To correct this, you can avoid using ax.twinx and overlay 2 graphs instead:

# 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:

叠加条形图和线图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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