Matplotlib 散点图图例
- 2025-02-20 09:24:00
- admin 原创
- 78
问题描述:
我创建了一个 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)
我尝试更改Line2D
为Scatter
并scatter
返回Scatter
错误并scatter
更改图表并返回错误。
使用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)
当我运行这个时,图例不再存在,它是一个角落里的小白框,里面什么都没有。
有什么建议吗?
解决方案 1:
二维散点图
使用模块scatter
的方法matplotlib.pyplot
应该可以工作(至少对于 Python 2.7.5 的 matplotlib 1.2.1 来说是这样),如下面的示例代码所示。此外,如果您使用散点图,请在图例调用中使用scatterpoints=1
而不是 ,numpoints=1
以便每个图例条目只有一个点。
在下面的代码中,我使用了随机值,而不是一遍又一遍地绘制相同的范围,从而使所有图都可见(即不相互重叠)。
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()
3D 散点图
要绘制 3D 散点图,请使用plot
方法,因为图例不支持实例方法Patch3DCollection
返回的图例。要指定 markerstyle,您可以将其作为位置参数包含在方法调用中,如下例所示。也可以选择将参数包含在和参数中。scatter
`Axes3Dlinestyle
marker`
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()
解决方案 2:
如果您使用的是 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]
colors = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y, c=values, cmap=colors)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
解决方案 3:
其他答案看起来有点复杂,您只需在散点函数中添加一个参数“标签”,这将成为您的图表的图例。
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()
这是你的输出:
解决方案 4:
这是一个更简单的方法(来源:此处):
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()
你会得到这个:
点击此处查看图例属性
解决方案 5:
我创建了一个年份唯一值的图例列表,并将其用作散点图中的颜色。散点图变量称为结果。result.legend_elements()[0] 返回颜色列表,我使用 labels=legend(年份列表)将颜色图设置为值。
legend=[str(year) for year in df['year'].unique()]
plt.title('Battery Capicity kwh')
result = plt.scatter('Approx_Release_price_order_in_K$','Battery_Capacity_kWh',data=df,c='year',label='Class 1')
plt.ylabel('kwh')
plt.xlabel('K$')
plt.legend(handles=result.legend_elements()[0],
labels=legend,
title="Year")
print('The higher priced evs have more battery capacity')
扫码咨询,免费领取项目管理大礼包!