首页 > 解决方案 > matplotlib 为具有不同颜色的项目添加纯色图例键

问题描述

我发现 matplotlib 是最令人困惑的库之一:(

我正在使用轴的散点函数来绘制一些点,每个点都有自己的权重与之相关联,控制不透明度......

colors = [(*c[:3], w.item() / 1) for w in weight]
ax.scatter(gen, samples, c=colors, s=10, marker="*", label="$\\tilde{x}$", zorder=-100)
ax.legend

问题是图例中的颜色似乎是colors数组中的随机颜色。有时它是半透明的,因为散射中的某些颜色几乎是半透明的。我希望图例中的颜色是纯色的,同时保持散点图中的可变颜色。

我将如何做到这一点?

标签: pythonmatplotlib

解决方案


结果证明,仅更改图例句柄的 alpha 值比预期的要困难(显而易见的方法item.set_alpha(1)会导致一些几乎不可见的颜色出现问题)。但是您可以设置句柄颜色,使图例具有统一的外观:

from matplotlib import pyplot as plt

#fake data generation
import numpy as np
n = 10
np.random.seed(1234)
gen = np.random.randint(1, 10, n)
samples = np.random.randint(10, 50, n)
colors = np.random.rand(n, 4)
#reduce the alpha values for demonstration purposes
colors[:, 3] = colors[:, 3]/3


fig, ax = plt.subplots(figsize=(10,8))

ax.scatter(gen, samples, c=colors, s=70, marker="o", label="$\\tilde{y}$", zorder=-100)
ax.scatter(samples, gen, c=colors, s=50, marker="x", label="$\\tilde{x}$", zorder=-100)

l = ax.legend()

for item in l.legendHandles:
    item.set_color("black")

plt.show()

样本输出: 在此处输入图像描述


推荐阅读