python - Matplotlib:如何根据 LineCollection 的坐标更改其颜色?

标签 python matplotlib colors

考虑以下情节:

enter image description here

fig, ax = plt.subplots(figsize = (14, 6))
ax.set_facecolor('k')
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)

xs = np.arange(60, 70)          # xs = np.linspace(60, 70, 100)
ys = np.arange(0, 100, .5)      # ys = np.linspace(0, 100, 100)

v = [[[x, y] for x in xs] for y in ys]

lines = LineCollection(v, linewidth = 1, cmap = plt.cm.Greys_r)
lines.set_array(xs)
ax.add_collection(lines)

如何根据x改变线条的颜色坐标(水平)以创建如下所示的“阴影”效果:

enter image description here

在这里,更大的x是,“越白”LineCollection是。

按照这个推理,我认为指定 lines.set_array(xs)可以解决这个问题,但正如您在我的图中所看到的,颜色渐变仍然遵循 y 轴。奇怪的是,这种模式不断重复,从黑到白(每 5 次)一遍又一遍(最多 100 次)。

我认为(完全不确定)问题出在 v包含坐标的变量。 x 的串联和y可能不合适。

最佳答案

您提供给 LineCollection 的列表 v 的形状确实不适合创建所需方向的渐变。这是因为 LineCollection 中的每条线只能有单一颜色。这里,线条的范围从 x=60 到 x=70,每条线条都有一种颜色。

您需要做的是创建一个线条集合,其中每条线条分为多个段,每个段都可以有自己的颜色。

为此,一个维度数组(n, m, l),其中n是段数,m是每段的点数,l 是需要使用的维度(2D,因此 l=2)。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
fig, ax = plt.subplots(figsize = (14, 6))
ax.set_facecolor('k')
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)

xs = np.linspace(60, 70, 100)
ys = np.linspace(0, 100, 100)


X,Y = np.meshgrid(xs,ys)
s = X.shape
segs = np.empty(((s[0])*(s[1]-1),2,2))
segs[:,0,0] = X[:,:-1].flatten()
segs[:,1,0] = X[:,1:].flatten()
segs[:,0,1] = Y[:,:-1].flatten()
segs[:,1,1] = Y[:,1:].flatten()

lines = LineCollection(segs, linewidth = 1, cmap = plt.cm.Greys_r)
lines.set_array(X[:,:-1].flatten())
ax.add_collection(lines)

plt.show()

enter image description here

关于python - Matplotlib:如何根据 LineCollection 的坐标更改其颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48350675/

相关文章:

javascript - 通过 RGB 确定颜色亮度

java - JButton setBackground 不起作用

python - 在不执行的情况下在 Python 中格式化 SQL 查询

Python-Matplotlib : Define Individual Legend Entries

python - 如何更快地使用 Google map 进行地理编码?

python - Pandas :如何在散点图中绘制一条线并将其带​​到后面/前面?

python - 给定起始颜色和中间颜色,如何获得剩余颜色? (Python)

colors - 减去颜色值时出现 LESS CSS 编译错误

python - 如何在 numpy 中进行分散和聚集操作?

python - 第 1 行的 SyntaxError : Non-UTF-8 code starting with '\x90' in file C:\Python36\python. exe,但未声明编码