【发布时间】:2020-09-16 07:44:06
【问题描述】:
我有以下代码片段(c、s、x、y 的值是模型,但真正的列表遵循相同的格式,只是更大。只使用了两种颜色 - 红色和绿色。所有列表都是大小相同)
问题是颜色图例未能实现。我完全不知道为什么。图例生成的代码 sn-ps 基本上是从文档中剪切粘贴,即 (https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html#sphx-glr-gallery-lines-bars-and-markers-scatter-with-legend-py)
有人知道吗?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
c = [ 'g', 'r', 'r', 'g', 'g', 'r', 'r', 'r', 'g', 'r']
s = [ 10, 20, 10, 40, 60, 90, 90, 50, 60, 40]
x = [ 2.4, 3.0, 3.5, 3.5, 3.5, 3.5, 3.5, 2.4, 3.5, 3.5]
y = [24.0, 26.0, 20.0, 19.0, 19.0, 21.0, 20.0, 23.0, 20.0, 20.0]
fig, ax = plt.subplots()
scatter = plt.scatter(x, y, s=s, c=c, alpha=0.5)
# produce a legend with the unique colors from the scatter
handles, lables = scatter.legend_elements()
legend1 = ax.legend(handles, labels, loc="lower left", title="Colors")
ax.add_artist(legend1)
# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.5)
legend2 = ax.legend(handles, labels, loc="upper right", ncol=2, title="Sizes")
plt.show()
绘图输出:
【问题讨论】:
-
你试过像
legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Colors")这样的实际代码 -
@Sheldore 尝试了相同的结果。请参阅下面发布的解决方法。谢谢。
标签: python matplotlib colors legend legend-properties