簡體   English   中英

Plot seaborn 中多列的條形圖和線圖

[英]Plot a barplot AND lineplot with multiple columns in seaborn

我正在嘗試使用 seaborn 為 plot 繪制多列 dataframe 的條形圖,而在第二個 y 軸上,我 plot 繪制多列 dataframe 的線圖。 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?

這是因為條形圖使用 [0, 1, 2...] 作為 x 值,即使有帶有 2015、2016、2017... 的標簽,而線圖使用 2015、2016、2017...

要更正此問題,您可以避免使用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:

疊加條形圖和線圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM