Add Legend to Seaborn point plot

后端 未结 3 1102
孤街浪徒
孤街浪徒 2020-12-09 02:50

I am plotting multiple dataframes as point plot using seaborn. Also I am plotting all the dataframes on the same axis.

How wou

相关标签:
3条回答
  • 2020-12-09 03:16

    I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

    import matplotlib.patches as mpatches
    red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
    black_patch = mpatches.Patch(color='#000000', label='Label2')
    

    In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

    plt.legend(handles=[red_patch, black_patch])
    

    And the legend ought to appear in the pointplot.

    0 讨论(0)
  • 2020-12-09 03:21

    I would suggest not to use seaborn pointplot for plotting. This makes things unnecessarily complicated.
    Instead use matplotlib plot_date. This allows to set labels to the plots and have them automatically put into a legend with ax.legend().

    import matplotlib.pyplot as plt
    import pandas as pd
    import seaborn as sns
    import numpy as np
    
    date = pd.date_range("2017-03", freq="M", periods=15)
    count = np.random.rand(15,4)
    df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
    df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
    df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
    
    f, ax = plt.subplots(1, 1)
    x_col='date'
    y_col = 'count'
    
    ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
    ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
    ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
    
    ax.legend()
    
    plt.gcf().autofmt_xdate()
    plt.show()
    


    In case one is still interested in obtaining the legend for pointplots, here a way to go:

    sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
    sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
    sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
    
    ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
    
    ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
    plt.gcf().autofmt_xdate()
    
    plt.show()
    
    0 讨论(0)
  • 2020-12-09 03:26

    Old question, but there's an easier way.

    sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
    sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
    sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
    plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])
    

    This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.

    0 讨论(0)
提交回复
热议问题