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

我尝试了this建议,如果我的两个系列绘图都具有不同的点类型(而不是线和点),则该建议会很好。
我当前使用的代码带有不正确的图例,是

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()


您是否有解决此问题的建议?

最佳答案

在这种情况下,将我的答案应用于How to create two legend objects for a single plot instance?

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()


python - 在图例中使用线和点标记为两个图共享相同的标签-LMLPHP

关于python - 在图例中使用线和点标记为两个图共享相同的标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54685373/

10-10 14:50