【发布时间】:2018-08-24 03:42:43
【问题描述】:
我通过下面的代码通过 matplotlib 获得了一个示例散点图。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 100, 501)
y = np.sin(x)
label = 'xy data sample'
plt.scatter(x, y, cmap='plasma', c=x, label=label)
legend_dict = dict(ncol=1, loc='best', scatterpoints=4, fancybox=True, shadow=True)
plt.legend(**legend_dict)
plt.show()
运行上面的代码会产生下面的图。
颜色图已成功绘制,但图例显示的点都是蓝色的,而不是与所选颜色图对应的颜色的点。为什么会这样?
我尝试将cmap='plasma' 放入legend_dict,但会导致以下错误。
File "/Users/.../
site-packages/matplotlib/axes/_axes.py", line 550, in legend
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'cmap'
编辑:
我想要的输出是通过选择的颜色图让图例中表示的四个点成为不同的颜色。理想情况下,本例中的cmap='plasma' 可以使用类似于蓝点、紫点、橙红点、黄点的图例生成图例。虽然颜色条可以作为一种可能的替代方案,但我还没有查看任何关于颜色条的文档。
【问题讨论】:
-
发生这种情况的原因是 matplotlib 就是这样设计的。您希望积分具有其他哪种颜色?请写清楚你想要达到的目标。
-
颜色条会更适合这个吗?否则,您将有很多图例条目。可能是this 之类的东西?
-
我更新了帖子来解决这个问题。
标签: python matplotlib legend scatter-plot colormap