Search code examples
pythonseabornvisualizationlegendline-plot

How to display all numeric legend values in seaborn


I am trying to create a sns.lineplot() for following dataframe:

overs:

    season  over    total_runs  total_overs avg_run
0   2008    1            703       745     0.943624
1   2008    2            923       741     1.245614
2   2008    3            826       727     1.136176
3   2008    4            912       725     1.257931
4   2008    5            1017      722     1.408587
235 2019    16           1099      721     1.524272
236 2019    17           1035      707     1.463932
237 2019    18           1124      695     1.617266
238 2019    19           1209      669     1.807175
239 2019    20           1189      552     2.153986
240 rows × 5 columns

sns.lineplot(x='avg_run', y='over', hue='season', data='overs')

I'm getting the output as follows:

Output

  • I'm not getting legends for all the season (in the range: 2008-2019) and I'm not able to distinguish between the current lineplots.
  • Please note: my requirement is to plot all lines in the same figure

Solution

    • Try using the legend='full' parameter for seaborn.lineplot()
      • This can be necessary when the legend values are numeric.
    • There are different color palettes to choose from.
    import pandas as pd
    import numpy as np
    import seaborn as sns
    
    # test data
    sample_length = range(1, 6+1)
    rads = np.arange(0, 2*np.pi, 0.01)
    data = np.array([np.sin(t*rads) for t in sample_length])
    df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=sample_length)
    
    dfl = df.stack().reset_index().rename(columns={'level_1': 'frequency', 0: 'amplitude'})
    
    # plot
    sns.lineplot(x='radians', y='amplitude', hue='frequency', data=dfl, legend='full', palette='winter')
    

    enter image description here

    custom colormap

    • Select a palette with enough unique colors for the number of lines in the plot.
    • Additional options for the husl palette can be found at seaborn.husl_palette
    • colors can also be a list of manually selected colors
      • colors = ['red', 'blue', 'green', 'black', 'purple', 'yellow']
    # create color mapping based on all unique values of frequency
    freqs = dfl.frequency.unique()
    colors = sns.color_palette('husl', n_colors=len(freqs))  # get a number of colors
    cmap = dict(zip(freqs, colors))  # zip freqs to colors and create a dict
    
    sns.lineplot(x='radians', y='amplitude', hue='frequency', data=dfl, legend='full', palette=cmap)