Python Matplotlib 散点图图例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17411940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:07:50  来源:igfitidea点击:

Matplotlib scatter plot legend

pythonmatplotliblegendscatter-plot

提问by user2386081

I created a 4D scatter plot graph to represent different temperatures in a specific area. When I create the legend, the legend shows the correct symbol and color but adds a line through it. The code I'm using is:

我创建了一个 4D 散点图来表示特定区域的不同温度。当我创建图例时,图例显示了正确的符号和颜色,但在其中添加了一条线。我正在使用的代码是:

colors=['b', 'c', 'y', 'm', 'r']
lo = plt.Line2D(range(10), range(10), marker='x', color=colors[0])
ll = plt.Line2D(range(10), range(10), marker='o', color=colors[0])
l = plt.Line2D(range(10), range(10), marker='o',color=colors[1])
a = plt.Line2D(range(10), range(10), marker='o',color=colors[2])
h = plt.Line2D(range(10), range(10), marker='o',color=colors[3])
hh = plt.Line2D(range(10), range(10), marker='o',color=colors[4])
ho = plt.Line2D(range(10), range(10), marker='x', color=colors[4])
plt.legend((lo,ll,l,a, h, hh, ho),('Low Outlier', 'LoLo','Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),numpoints=1, loc='lower left', ncol=3, fontsize=8)

I tried changing Line2Dto Scatterand scatter. Scatterreturned an error and scatterchanged the graph and returned an error.

我尝试更改Line2DScatterscatterScatter返回错误并scatter更改图形并返回错误。

With scatter, I changed the range(10)to the lists containing the data points. Each list contains either the x, y, or z variable.

使用scatter,我将 更改为range(10)包含数据点的列表。每个列表包含 x、y 或 z 变量。

lo = plt.scatter(xLOutlier, yLOutlier, zLOutlier, marker='x', color=colors[0])
ll = plt.scatter(xLoLo, yLoLo, zLoLo, marker='o', color=colors[0])
l = plt.scatter(xLo, yLo, zLo, marker='o',color=colors[1])
a = plt.scatter(xAverage, yAverage, zAverage, marker='o',color=colors[2])
h = plt.scatter(xHi, yHi, zHi, marker='o',color=colors[3])
hh = plt.scatter(xHiHi, yHiHi, zHiHi, marker='o',color=colors[4])
ho = plt.scatter(xHOutlier, yHOutlier, zHOutlier, marker='x', color=colors[4])
plt.legend((lo,ll,l,a, h, hh, ho),('Low Outlier', 'LoLo','Lo', 'Average', 'Hi', 'HiHi',     'High Outlier'),scatterpoints=1, loc='lower left', ncol=3, fontsize=8)

When I run this, the legend no longer exists, it is a small white box in the corner with nothing in it.

当我运行它时,图例不再存在,它是角落里的一个白色小盒子,里面什么也没有。

Any advice?

有什么建议吗?

采纳答案by sodd

2D scatter plot

二维散点图

Using the scattermethod of the matplotlib.pyplotmodule should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1rather than numpoints=1in the legend call to have only one point for each legend entry.

使用模块的scatter方法matplotlib.pyplot应该可以工作(至少在 matplotlib 1.2.1 和 Python 2.7.5 中),如下面的示例代码所示。此外,如果您使用散点图,请使用scatterpoints=1而不是numpoints=1在图例调用中为每个图例条目只有一个点。

In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).

在下面的代码中,我使用了随机值,而不是一遍又一遍地绘制相同的范围,使所有的图都可见(即彼此不重叠)。

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()

enter image description here

在此处输入图片说明

3D scatter plot

3D散点图

To plot a scatter in 3D, use the plotmethod, as the legend does not support Patch3DCollectionas is returned by the scattermethod of an Axes3Dinstance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyleand markerparameters.

要在 3D 中绘制散点图,请使用plot方法,因为图例不支持实例方法Patch3DCollection返回的 as 。要指定标记样式,您可以将其作为位置参数包含在方法调用中,如下例所示。可选地,可以将参数包含在和参数中。scatterAxes3Dlinestylemarker

import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()

enter image description here

在此处输入图片说明

回答by Amir

Here's an easier way of doing this (source: here):

这是一种更简单的方法(来源:此处):

import matplotlib.pyplot as plt
from numpy.random import rand


fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    n = 750
    x, y = rand(2, n)
    scale = 200.0 * rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')

ax.legend()
ax.grid(True)

plt.show()

And you'll get this:

你会得到这个:

enter image description here

在此处输入图片说明

Take a look at herefor legend properties

看看这里的图例属性

回答by Avelanche

Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.

其他答案似乎有点复杂,您只需在 scatter 函数中添加一个参数“标签”,这将成为您绘图的图例。

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=4)

plt.show()

Here is your output

这是你的输出

回答by OliverQ

if you are using matplotlib version 3.1.1 or above, you can try:

如果您使用的是 matplotlib 3.1.1 或更高版本,您可以尝试:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)

results2

结果2