我正在尝试制作一个散点图,在框外有一个图形图例,正如如何将图例放在图之外所建议的那样,但我也在绘制多组数据一个用于多个散点图的颜色条。下面的最小工作示例删除了大部分集合,实际脚本中可以有 10 个集合:
import matplotlib.pyplot as plt
norm = plt.Normalize(55,1954)
plt.scatter([75,75,63,145,47],[0.979687,1.07782,2.83995,4.35468,4.44244], c = [75,75,70,70,70], norm = norm, label = 's1', cmap = 'gist_rainbow', marker = 'o')
plt.scatter([173,65],[0.263218,3.12112], c = [77,68], norm = norm, label = 's2', cmap = 'gist_rainbow', marker = 'v')
plt.colorbar().set_label('score')
plt.legend(loc = "outside center left")
plt.savefig('file.svg', bbox_inches='tight', pad_inches = 0.1)
但我收到错误:
/home/con/.local/lib/python3.10/site-packages/matplotlib/projections/__init__.py:63: UserWarning: Unable to import Axes3D. This may be due to multiple versions of Matplotlib being installed (e.g. as a system package and as a pip package). As a result, the 3D projection is not available.
warnings.warn("Unable to import Axes3D. This may be due to multiple versions of "
Traceback (most recent call last):
File "/tmp/2Le599Dl8S.py", line 6, in <module>
plt.legend(loc = "outside center left")
File "/home/con/.local/lib/python3.10/site-packages/matplotlib/pyplot.py", line 3372, in legend
return gca().legend(*args, **kwargs)
File "/home/con/.local/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 323, in legend
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
File "/home/con/.local/lib/python3.10/site-packages/matplotlib/legend.py", line 566, in __init__
self.set_loc(loc)
File "/home/con/.local/lib/python3.10/site-packages/matplotlib/legend.py", line 703, in set_loc
raise ValueError(
ValueError: 'outside' option for loc='outside center left' keyword argument only works for figure legends
我也尝试过:
import matplotlib.pyplot as plt
norm = plt.Normalize(55,1954)
fig = plt.scatter([75,75,63,145,47],[0.979687,1.07782,2.83995,4.35468,4.44244], c = [75,75,70,70,70], norm = norm, label = 's1', cmap = 'gist_rainbow', marker = 'o')
plt.scatter([173,65],[0.263218,3.12112], c = [77,68], norm = norm, label = 's2', cmap = 'gist_rainbow', marker = 'v')
plt.colorbar().set_label('score')
fig.legend(loc = "outside center left")
plt.savefig('file.svg', bbox_inches='tight', pad_inches = 0.1)
但这又产生了另一个问题:
/home/con/.local/lib/python3.10/site-packages/matplotlib/projections/__init__.py:63: UserWarning: Unable to import Axes3D. This may be due to multiple versions of Matplotlib being installed (e.g. as a system package and as a pip package). As a result, the 3D projection is not available.
warnings.warn("Unable to import Axes3D. This may be due to multiple versions of "
Traceback (most recent call last):
File "/tmp/2Le599Dl8S.py", line 6, in <module>
fig.legend(loc = "outside center left")
AttributeError: 'PathCollection' object has no attribute 'legend'
我还查看了matplotlib 中 plt.figure() 的必要性是什么?,但是里面没有关于图例的内容,所以那篇文章没有解决我的问题。它也没有出现在谷歌搜索中。
你快到了。您只需创建一个
plt.Figure()
然后使用fig.legend()
.