gpt4 book ai didi

python - matplotlib 中的 gnuplot linecolor 变量?

转载 作者:太空狗 更新时间:2023-10-29 22:04:21 25 4
gpt4 key购买 nike

我有一个 y 值数组,它们形成一条线。此外,我有一个数组,其元素数与值范围为 0 到 1 的 y 数组的元素数相同。我们将此数组称为“z”。我想绘制 y 值数组,以便每个点的颜色与 z 值相对应。

在 gnuplot 中,您可以使用“lc 变量”执行此操作:

plot ’data’ using 1:2:3 with points lc variable  

使用此处的建议:Matplotlib scatterplot; colour as a function of a third variable ,我能够使用散点图,它确实有效:

import matplotlib as mpl  
import matplotlib.pyplot as plt

plt.scatter(x, y, c=z, s=1, edgecolors='none', cmap=mpl.cm.jet)
plt.colorbar()
plt.show()

有没有办法用 matplotlib 中的 plot 方法来做到这一点,类似于这个?

plt.plot(x, y, c=z)

当我尝试上面的代码时,所有的行都显示为黑色。

最佳答案

我遇到了同样的问题:想要绘制颜色不均匀的线条,我希望它依赖于第三个变量 (z)。

但我绝对想使用一条线,而不是标记(如@joaquin 的回答)。我在 matplotlib gallery example 中找到了解决方案,使用类 matplotlib.collections.LineCollection(链接 here)。

这是我的示例,它在 basemap 中绘制轨迹,并根据其高度为它们着色:

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.collections import LineCollection
import numpy as np

m = Basemap(llcrnrlon=-42,llcrnrlat=0,urcrnrlon=5,urcrnrlat=50, resolution='h')
fig = plt.figure()
m.drawcoastlines()
m.drawcountries()

for i in trajectorias:
# for each i, the x (longitude), y (latitude) and z (height)
# are read from a file and stored as numpy arrays

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

lc = LineCollection(segments, cmap=plt.get_cmap('Spectral'),
norm=plt.Normalize(250, 1500))
lc.set_array(z)
lc.set_linewidth(2)

plt.gca().add_collection(lc)

axcb = fig.colorbar(lc)
axcb.set_label('cota (m)')

plt.show()

height dependent trajectories

关于python - matplotlib 中的 gnuplot linecolor 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com