python - 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
数组中的随机颜色。有时它是半透明的,因为散射中的某些颜色几乎是半透明的。我希望图例中的颜色是纯色的,同时保持散点图中的可变颜色。
我将如何做到这一点?
解决方案
结果证明,仅更改图例句柄的 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()
推荐阅读
- r - R for 循环:何时在 seq_along(x) 中使用 i 以及何时在 x 中使用 i
- android - Flutter:ListView内的ListView不滚动
- matlab - 如何调整组合图中单条线的线宽?
- android - 最新的 Android NDK (r21c) 的 libbinder_ndk 缺少几个导出的 API
- android - AppRTC:iOS 到 Android 呼叫不起作用
- python - 是否可以让 pathlib 将 Path 中的斜杠视为重要?
- python - 在 Python 中使应用函数更快
- ember.js - 如何预加载 ember 引擎?
- hibernate - 我应该使用哪个休眠版本?
- flutter - 如何在初始小部件构建后使 AnimatedContainer 更改高度,而不是在按钮单击上