【问题标题】:Add legend in Seaborn combo line bar chart在 Seaborn 组合折线图中添加图例
【发布时间】:2021-11-20 10:04:02
【问题描述】:

我正在尝试向我的 seaborn 条形图 + 折线图添加一个图例,但只收到错误消息“没有找到带有标签的句柄放入图例”。无论我尝试什么。这个怎么办?

from pathlib import Path
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import numpy as np    

dfGroup = pd.DataFrame({
        'Year': [1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920],
        'Total Deaths': [0, 0, 2, 3, 2, 3, 4, 5, 6, 7, 8],
        'Total Affected': [0, 1, 0, 2, 3, 6, 9, 8, 12, 13, 15]
        })
# Add 3-year rolling average
dfGroup['rolling_3years'] = dfGroup['Total Deaths'].rolling(3).mean().shift(0)
dfGroup = dfGroup.fillna(0)

# Make a smooth line from the 3-year rolling average
from scipy.interpolate import make_interp_spline
X_Y_Spline = make_interp_spline(dfGroup['Year'], dfGroup['rolling_3years'])
 
# Returns evenly spaced numbers over a specified interval.
X_ = np.linspace(dfGroup['Year'].min(), dfGroup['Year'].max(), 500)
Y_ = X_Y_Spline(X_)

# Plot the data
a4_dims = (15, 10)
fig, ax1 = plt.subplots(figsize=a4_dims)

ax1 = sns.barplot(x = "Year", y = "Total Deaths",
             data = dfGroup, color='#42b7bd')
ax2 = ax1.twinx()
ax2 = sns.lineplot(X_, Y_, marker='o')

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    由于 seaborn 的 barplot 使用分类位置,内部编号为 0,1,2,... 的两个图可以绘制在同一个 ax 上。这可以通过重新计算lineplotx 值来完成。

    要获得图例,应使用label= 关键字。 (在twinx 轴上创建图例有点复杂,并且需要创建自定义句柄。)Seaborn 通常会自动创建图例。如果你想改变它的外观,你可以通过自定义参数调用ax1.legend(...)

    下面是一些示例代码:

    from pathlib import Path
    import pandas as pd
    import seaborn as sns
    from matplotlib import pyplot as plt
    import matplotlib.dates as mdates
    import numpy as np
    
    dfGroup = pd.DataFrame({
        'Year': [1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920],
        'Total Deaths': [0, 0, 2, 3, 2, 3, 4, 5, 6, 7, 8],
        'Total Affected': [0, 1, 0, 2, 3, 6, 9, 8, 12, 13, 15]
    })
    # Add 3-year rolling average
    dfGroup['rolling_3years'] = dfGroup['Total Deaths'].rolling(3).mean().shift(0)
    dfGroup = dfGroup.fillna(0)
    
    # Make a smooth line from the 3-year rolling average
    from scipy.interpolate import make_interp_spline
    
    X_Y_Spline = make_interp_spline(dfGroup['Year'], dfGroup['rolling_3years'])
    
    # Returns evenly spaced numbers over a specified interval.
    X_ = np.linspace(dfGroup['Year'].min(), dfGroup['Year'].max(), 500)
    Y_ = X_Y_Spline(X_)
    
    # Plot the data
    a4_dims = (15, 10)
    fig, ax1 = plt.subplots(figsize=a4_dims)
    sns.barplot(x="Year", y="Total Deaths",
                data=dfGroup, color='#42b7bd', label='Barplot label', ax=ax1)
    x_plot = np.linspace(0, len(dfGroup) - 1, len(X_))
    sns.lineplot(x=x_plot, y=Y_, marker='o', label='LinePlot label', ax=ax1)
    ax1.set_ylim(ymin=0) # let bars touch the bottom of the plot
    ax1.margins(x=0.02) # less margins left and right
    # ax1.legend(title='legend title') # optionally change the legend
    plt.show()
    

    PS:如果 ax 已经创建,它应该作为 seaborn 的 axes-level functions 的参数提供(所以,sns.barplot(..., ax=ax1) 而不是 ax1 = sns.barplot(...)

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 2021-08-06
      • 1970-01-01
      • 2020-08-08
      • 2021-03-24
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      相关资源
      最近更新 更多