首页 > 解决方案 > 在图例中使用线和点标记为两个绘图共享相同的标签

问题描述

我有一个包含两个不同系列曲线的图,我将使用点和线来绘制它们。我想要一个图例,使线和点标记共享相同的标签。

如果我的两个系列的图有不同的点类型,而不是线和点,我已经尝试过这个建议。我目前使用的代码,带有不正确的图例,是

import numpy as np
import matplotlib.pyplot as plt

Vs = np.array([0.5, 1, 1.5, 2])
Xs = np.array([[ 0.5, 0.2,  0.7],
  [ 0.5, 0.3,  0.9],
  [ 0.5, 0.5, 0.4],
  [ 0.5, 0.7, 0.4],
  [ 0.5, 0.9, 0.7],
  [ 1, 0.15,  0.9],
  [ 1, 0.35, 0.6],
  [ 1, 0.45, 0.6],
  [ 1, 0.67, 0.5],
  [ 1, 0.85, 0.9],
  [ 1.5, 0.1,  0.9],
  [ 1.5, 0.3, 0.7],
  [ 1.5, 0.76, 0.3],
  [ 1.5, 0.98, 0.4],
  [ 2, 0.21, 0.5],
  [ 2, 0.46, 0.4],
  [ 2, 0.66, 0.3],
  [ 2, 0.76, 0.5],
  [ 2, 0.88, 0.4],
  [ 2, 0.99, 0.4]])


 f, axs = plt.subplots(1, 1, figsize=(2.5,3))
 #-------------------------------------
 axs.set_xlim(0.38,1.0)
 axs.set_ylim(0.0,4.0)
 colors = plt.cm.gist_ncar(np.linspace(0,1,max(Vs)+3))
 for idx,Val in enumerate(Vs):
     axs.plot(Xs[Xs[:,0] == Val ,1], Xs[Xs[:,0] == Val ,2],'s',label=r"$Y={}$".format(Val), ms=3, color=colors[idx])
     axs.plot(Xs[Xs[:,0] == Val ,1], Xs[Xs[:,0] == Val ,2]*Val/0.3,'-', label=r"$Y={}$".format(Val), ms=3, color=colors[idx])


axs.set_ylim(0.0,4.0)
axs.set_ylabel(r"$Y$    ", labelpad=2)
axs.set_xlabel(r"$X$    ", labelpad=2)
axs.set_yticks([0,0.5,1.0,1.5,2.0, 2.5, 3.0, 3.5, 4.0])
axs.set_xticks([0,0.5,1.0])

axs.legend(fontsize=6, loc=2, numpoints = 1, labelspacing=0.2,handletextpad=0.2, frameon=False)

f.savefig("tmp.pdf")
plt.show()

你有什么建议来解决这个问题吗?

标签: pythonmatplotliblegend

解决方案


将我的答案应用于如何为单个绘图实例创建两个图例对象?在这种情况下:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib

Vs = np.array([0.5, 1, 1.5, 2])
Xs = np.array([[ 0.5, 0.2,  0.7], [ 0.5, 0.3,  0.9], [ 0.5, 0.5, 0.4],
               [ 0.5, 0.7, 0.4],[ 0.5, 0.9, 0.7], [ 1, 0.15,  0.9],
               [ 1, 0.35, 0.6], [ 1, 0.45, 0.6], [ 1, 0.67, 0.5],
               [ 1, 0.85, 0.9], [ 1.5, 0.1,  0.9], [ 1.5, 0.3, 0.7],
               [ 1.5, 0.76, 0.3], [ 1.5, 0.98, 0.4], [ 2, 0.21, 0.5], 
               [ 2, 0.66, 0.3], [ 2, 0.76, 0.5], [ 2, 0.88, 0.4],
               [ 2, 0.99, 0.4]])


f, axs = plt.subplots(1, 1, figsize=(2.5,3))

axs.set_xlim(0.38,1.0)
axs.set_ylim(0.0,4.0)
colors = plt.cm.gist_ncar(np.linspace(0,1,max(Vs)+3))
for idx,Val in enumerate(Vs):
    axs.plot(Xs[Xs[:,0] == Val ,1], Xs[Xs[:,0] == Val ,2],'s',label=r"$Y={}$".format(Val), ms=3, color=colors[idx])
    axs.plot(Xs[Xs[:,0] == Val ,1], Xs[Xs[:,0] == Val ,2]*Val/0.3,'-', label=r"$Y={}$".format(Val), ms=3, color=colors[idx])


axs.set_ylim(0.0,4.0)
axs.set_ylabel(r"$Y$    ", labelpad=2)
axs.set_xlabel(r"$X$    ", labelpad=2)
axs.set_yticks([0,0.5,1.0,1.5,2.0, 2.5, 3.0, 3.5, 4.0])
axs.set_xticks([0,0.5,1.0])

h, l = axs.get_legend_handles_labels()
axs.legend(handles=zip(h[::2], h[1::2]), labels=l[::2], 
           handler_map = {tuple: matplotlib.legend_handler.HandlerTuple(None)})


plt.show()

在此处输入图像描述


推荐阅读