0

I got this data:

reg_month no_ses_users ses_users no_ses_users_ptc
0 2021-01-01 29 101 22.31
1 2021-02-01 48 188 20.34
2 2021-03-01 86 303 22.11
3 2021-04-01 111 381 22.56
4 2021-05-01 141 479 22.74
5 2021-06-01 177 564 23.89
6 2021-07-01 224 661 25.31
7 2021-08-01 257 746 25.62
8 2021-09-01 289 832 25.78
9 2021-10-01 319 934 25.46
10 2021-11-01 341 1019 25.07
11 2021-12-01 384 1111 25.69
12 2022-01-01 422 1203 25.97
13 2022-02-01 451 1292 25.87
14 2022-03-01 482 1377 25.93
15 2022-04-01 518 1468 26.08
16 2022-05-01 544 1553 25.94
17 2022-06-01 584 1633 26.34
18 2022-07-01 620 1722 26.47
19 2022-08-01 651 1813 26.42
20 2022-09-01 662 1847 26.39

I make graph with second axis with plt.bar (y axis), plt.plot (second y axis):

    import matplotlib.pyplot as plt
    import seaborn as sns

    sns.set_style('darkgrid')

    fig, ax = plt.subplots(figsize=(10, 6))
    
    ax1 = plt.bar(
        x=df2_3['reg_month'],
        height=df2_3['ses_users'],
        label='Users with sessions',
        edgecolor = 'black',
        linewidth = 0,
        width=20,
        color = '#3049BF'
    )
    
    ax2 = plt.bar(
        x=df2_3['reg_month'],
        height=df2_3['no_ses_users'],
        bottom=df2_3['ses_users'],
        label='Users without sessions',
        edgecolor = 'black',
        linewidth = 0,
        width=20,
        color = '#BF9530'
    )
    
    secax = ax.twinx()
    secax.set_ylim(min(df2_3['no_ses_users_ptc'])*0.5, max(df2_3['no_ses_users_ptc'])*1.1)

    ax3 = plt.plot(
        df2_3['reg_month'],
        df2_3['no_ses_users_ptc'],
        color = '#E97800',
        label='Users without sessions, ptc'
    )
    
    ax.legend()
    secax.legend()
    
    plt.show()

How can I delete white stipes and unite the legend at one?

Output: plt.show

John Doe
  • 95
  • 6

1 Answers1

1

To combine the legends, you need to get the individual handles & labels for ax and secax, combine them and plot the same. The white lines you are seeing are the grid lines. You can turn them off using axes.grid(False). Add these lines just before plt.show() (and comment out your exsting legend lines) like below...

ax.grid(False)    ## Turn off grid lines for ax
secax.grid(False) ## Turn off grid lines for secax

h1, l1 = ax.get_legend_handles_labels()    ## Get the legend handles and labels for ax
h2, l2 = secax.get_legend_handles_labels() ## Get the legend handles and labels for secax

handles = h1 + h2  ## Combine handles
labels = l1 + l2   ## Combine labels
ax.legend(handles, labels)  ## Plot the combined legend

#ax.legend()    ## Need to comment out
#secax.legend() ## Need to comment out

plt.show()

enter image description here

Redox
  • 9,321
  • 5
  • 9
  • 26