Matplotlib:在同一个图例下将不同的散布标记分组 [英] Matplotlib: Group different scatter markers under the same legend
问题描述
关于Matplotlib图,我有以下问题.
I have the following question about a Matplotlib plot.
我正在将来自不同实验的数据绘制为散点图;每个数据集都有自己的标记和颜色. 我希望将它们分组在图例的一行中,因为对我而言,它们具有相同的含义". Es. 假设我有3个研究小组的3组数据:
I am plotting data from different experiment as scatter plot; each of the set of data has its own marker and color. I would like to have them grouped in one single line of the legend because for me they have all the same "meaning". Es. Let's say I have 3 set of data from 3 research group:
plt.plot(group1, marker='^', c='r', label='groupdata')
plt.plot(group2, marker='o', c='b', label='groupdata')
plt.plot(group3, marker='s', c='g', label='groupdata')
我想在图例中显示一行:
I'd like to have a single line in legend that shows:
^ o s = groupdata
向我展示我的意思的最好方法是这张糟糕的图画; D
The best way to show you what I mean is this awfull drawing ;D
如所建议的,一个可行的例子;如您所见,图例中有3行,所有数据都命名为"groupdata";我想知道是否可以将它们分组在同一图例行下.
As suggested, a working example; as you can see I got 3 lines in the legend, all the data are named 'groupdata'; I'd like to know if it is possible to group them under the same legend line.
import matplotlib.pyplot as plt
import numpy as np
group1 = np.array([[1,4,6],[3,2,5]])
group2 = np.array([[1,5,9],[2,2,5]])
group3 = np.array([[1,4,2],[11,2,7]])
plt.plot(group1[0,:],group1[1,:], 'ro', marker='^', label='groupdata')
plt.plot(group2[0,:],group2[1,:], 'bo', marker='o', label='groupdata')
plt.plot(group3[0,:],group3[1,:], 'go', marker='s', label='groupdata')
plt.legend()
plt.show()
感谢您的帮助
推荐答案
找到了!
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import numpy as np
group1 = np.array([[1,4,6],[3,2,5]])
group2 = np.array([[1,5,9],[2,2,5]])
group3 = np.array([[1,4,2],[11,2,7]])
a, =plt.plot(group1[0,:],group1[1,:], 'ro', marker='^')
b, =plt.plot(group2[0,:],group2[1,:], 'bo', marker='o')
c, =plt.plot(group3[0,:],group3[1,:], 'go', marker='s')
plt.legend([(a,b,c)], ['goupdata'], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)})
plt.show()
非常感谢至少尝试提供帮助的人!
Thanks very much to anyone that at least tried to help!
更新: 我发现有用的东西;如果要添加多个条目:
Update: Something that i found useful; If you want to add more than one entries:
plt.legend([(a,b),(c)], ['goupdata1', 'groupdata2'], numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)})
这篇关于Matplotlib:在同一个图例下将不同的散布标记分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!