【问题标题】:Matplotlib: How to change the color of a LineCollection according to its coordinates?Matplotlib:如何根据坐标更改 LineCollection 的颜色?
【发布时间】:2018-01-19 22:50:49
【问题描述】:

考虑以下情节:

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 坐标(水平)更改线条的颜色,以创建像这样的“阴影”效果:

这里,x 越大,LineCollection 就越“白”。

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

我认为(完全不确定)问题在于包含坐标的v 变量。 xy 的串联可能不正确。

【问题讨论】:

  • 这里可能是最上面的情节:matplotlib.org/gallery/lines_bars_and_markers/…
  • 我一直在尝试这个,但是颜色会根据 y 轴发生变化,我不知道为什么。
  • 用你最近的尝试更新你的问题
  • 我放弃了,为此花了几个小时。垂直改变 LineSegment 的颜色是不可能的。
  • 这些问题询问的是横向而不是纵向。这两种选择都是可能的。正如在之前的评论中所指出的,您可以使用包括尝试的解决方案在内的清晰问题描述来更新您的问题。我敢肯定,您遇到的任何代码问题都可以轻松解决。

标签: python matplotlib colors


【解决方案1】:

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

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

为此,一个维度数组(n, m, l),其中n 是段数,m 是每个段的点数,l 是维度(二维,因此是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()

【讨论】:

  • 这很好解释。谢谢。
猜你喜欢
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 2022-09-23
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多