0

Despite similar questions, I haven't yet been able to solve my issue. I have a figure that, depending on the data, might have a very large legend, as shown below. Currently, the legend gets cut off (the plot itself is perfectly positioned so that's OK).

When I play with the figure in the viewer (as shown below), I can get it to move around somehow to start seeing more and more of the legend. How can I accomplish this code-wise? (I don't mind getting it as pdf or something else, as long as I can get the full view of what this viewer has under the hood).

When I try to change things like "set_position" in the code below, it doesn't help -- either the figure gets cut off or it's too small.

    fig, ax = plt.subplots()
    for t in list(set(df['t'])):
        subset = df[df['t'] == t]
        plt.scatter(subset.x, subset.y, c=subset.color, s=dot_size, label=t) 
  
    plt.ylim([-0.5 - 0.05, t.shape[0] - 0.5 + 0.05])
    plt.xlim([-0.5 - 0.05, t.shape[1] - 0.5 + 0.05])
    for tick in ax.get_xticklabels():
        tick.set_rotation(45)

    # shrink box figure so that the legend fits
    box = ax.get_position()
    ax.set_position([box.x0, box.y0 + box.height * 0.2,
                     box.width * 0.8, box.height * 0.8])

    plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=3, fontsize=7)

Any advice?

My next best option is to try to get the legend printed separately, which is not ideal.

enter image description here

Anon
  • 619
  • 1
  • 9
  • 18
  • I can reproduce the event if I have the data, but adding `plt.taught_layout=True` might help. Also, I don't know how many legends there are, but it looks like the number of columns could be expanded to `ncol=5`. – r-beginners Jul 12 '22 at 10:00
  • Thanks, I tried both (assuming you meant **tight_layout**), but still gets cut off unfortunately. – Anon Jul 12 '22 at 10:07
  • Typo. Also, would it improve if I try changing `bbox_to_anchor=(0.5,-0.7)`, which determines the position of the legend? – r-beginners Jul 12 '22 at 10:13
  • Tried that now - legend disappeared. – Anon Jul 12 '22 at 10:20
  • what matplotlib version are you using? It works perfectly fine for me with tight or constrained layout in version `3.5.2`. – Stef Jul 12 '22 at 12:32

0 Answers0