Two adjacent symbols in matplotlib legend

纵然是瞬间 提交于 2019-12-22 10:57:07

问题


I would like to identify two different symbols (with different colors) on the same line in a legend. Below, I tried doing this with Proxy Artists, but the result is that they get stacked on top of each other in the legend. I want them next to each other or one above the other-- so they are both visible.

from pylab import *
import matplotlib.lines as mlines

#define two colors, one for 'r' data, one for 'a' data
rcolor=[69./255 , 115./255, 50.8/255 ]
acolor=[202./255, 115./255, 50.8/255 ]

#Plot theory:
ax2.plot(rho, g_r, '-',color=rcolor,lw=2) 
ax2.plot(rho, g_a, '-',color=acolor,lw=2)  
#Plot experiment:
ax2.scatter(X_r, Y_r,s=200, marker='s', facecolors='none', edgecolors=rcolor); 
ax2.scatter(X_a, Y_a,s=200, marker='^', facecolors='none', edgecolors=acolor); 

#Create Proxy Artists for legend
expt_r = mlines.Line2D([], [], fillstyle='none', color=rcolor, marker='s', linestyle='', markersize=15)
expt_a = mlines.Line2D([], [], fillstyle='none', color=acolor, marker='^', linestyle='', markersize=15)
thry_r = mlines.Line2D([], [], fillstyle='none', color=rcolor, marker='', markersize=15)
thry_a = mlines.Line2D([], [], fillstyle='none', color=acolor, marker='', markersize=15)

#Add legend
ax2.legend(((expt_r,expt_a),(thry_r,thry_a)), ('Experiment','Theory'))

I think my problem is almost exactly like this one: (Matplotlib, legend with multiple different markers with one label), but it seems like the problem is unsolved since the answer there just plots one patch on top of the other, which is exactly what happens for me too. I feel like maybe I need to make a composite patch somehow, but I had trouble finding how to do this. Thanks!

Also, I haven't found how to make the legend symbols look the same (line thickness, size) as the scatter symbols. Thanks again.


回答1:


I do not answer your main question, sorry. However, regarding your last point

how to make the legend symbols look the same (line thickness, size) as the scatter symbols

you can use the keyword markerscale of the legend command. So for equal size

    ax2.legend( ...<handles_and_labels>...  , markerscale=1)

or a change of legend.markerscale in the rcParams should do.



来源:https://stackoverflow.com/questions/29452535/two-adjacent-symbols-in-matplotlib-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!