![](/img/trans.png)
[英]Setting different colors for markers and lines in matplotlib and show them in legend
[英]Legend for Lines with Different Endpoint Markers
我需要为线段创建一个图例,该线段在该线的底部和顶部具有不同的标记。 我能够创建一个图例,其中重复了 1 个标记符号,但不能在每一端创建两个不同的标记。
这是一个可重现的示例。
from matplotlib import pyplot as plt
import numpy as np
#Create some data
x = np.arange(0,11)
y1 = np.sqrt(x/2.)
y2 = x
plt.figure(figsize=(8,8))
ax = plt.subplot(111)
#Plot the lines
for i,x_ in zip(range(11),x):
ax.plot([x_,x_],[y1[i],y2[i]],c='k')
#Plot the end points
ax.scatter(x,y1,marker='s',c='r',s=100,zorder=10)
ax.scatter(x,y2,marker='o',c='r',s=100,zorder=10)
ax.plot([],[],c='k',marker='o',mfc='r',label='Test Range') #Create a single line for the label
ax.legend(loc=2,numpoints=2,prop={'size':16}) # How can I add a label with different symbols the line segments?
plt.show()
最终产品应该有一个带有符号的图例,该符号显示连接圆形和正方形的线。
恐怕您必须组合不同的mpatches
补丁,我不确定是否有更好的解决方案
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch
from matplotlib.legend_handler import HandlerLine2D
class HandlerCircle(HandlerPatch):
def create_artists(self,legend,orig_handle,
xdescent,ydescent,width,height,fontsize,trans):
center = 0.5 * width, 0.5 * height
p = mpatches.Circle(xy=center,radius=width*0.3)
self.update_prop(p,orig_handle,legend)
p.set_transform(trans)
return [p]
class HandlerRectangle(HandlerPatch):
def create_artists(self, legend, orig_handle,
xdescent, ydescent, width, height, fontsize, trans):
center = 0,height/2-width*0.5/2
width,height = width*0.5,width*0.5
p = mpatches.Rectangle(xy=center,width=width,height=width)
self.update_prop(p, orig_handle, legend)
p.set_transform(trans)
return [p]
fig,ax = plt.subplots(figsize=(12,8))
texts = ['','','Test Range']
line, = ax.plot([],[],c='k')
c = [mpatches.Circle((0.,0.,),facecolor='r',linewidth=.5),
line,
mpatches.Rectangle((0.,0.),5,5,facecolor='r',linewidth=.5)]
ax.legend(c,texts,bbox_to_anchor=(.25,.95),loc='center',ncol=3,prop={'size':20},
columnspacing=-1,handletextpad=.6,
handler_map={mpatches.Circle: HandlerCircle(),
line: HandlerLine2D(numpoints=0,),
mpatches.Rectangle: HandlerRectangle()}).get_frame().set_facecolor('w')
plt.show()
运行这个脚本,你会得到
如果您使用不同的图形大小或不同的图例大小,我上面脚本中的设置可能不是最佳的。 在这种情况下,您可以调整以下参数:
Circle
和Rectangle
的中心和大小columnspacing
ax.legend(...)
中的ax.legend(...)
columnspacing
和handletextpad
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.