使用颜色图更改线条颜色

2024-06-13 21:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多不同的文件(10-20),我从中读取x和y数据,然后绘制成一条线。 目前我有标准的颜色,但我想用彩色地图代替。 我看了很多不同的例子,但是不能正确地调整我的代码。 我希望颜色在每一行之间改变(而不是沿着这条线),使用颜色图,如gist_rainbow,即离散颜色图 下面的图片是我目前可以实现的。在

这就是我所尝试的:

import pylab as py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc, rcParams

numlines = 20
for i in np.linspace(0,1, numlines):
    color1=plt.cm.RdYlBu(1)
    color2=plt.cm.RdYlBu(2)

# Extract and plot data
data = np.genfromtxt('OUZ_QRZ_Lin_Disp_Curves')
OUZ_QRZ_per = data[:,1]
OUZ_QRZ_gvel = data[:,0]
plt.plot(OUZ_QRZ_per,OUZ_QRZ_gvel, '--', color=color1, label='OUZ-QRZ')

data = np.genfromtxt('PXZ_WCZ_Lin_Disp_Curves')
PXZ_WCZ_per = data[:,1]
PXZ_WCZ_gvel = data[:,0]
plt.plot(PXZ_WCZ_per,PXZ_WCZ_gvel, '--', color=color2, label='PXZ-WCZ')
# Lots more files will be plotted in the final code
py.grid(True)
plt.legend(loc="lower right",prop={'size':10})
plt.savefig('Test')
plt.show()

The Image I can produce now


Tags: pyimportdataplotmatplotlib颜色asnp
1条回答
网友
1楼 · 发布于 2024-06-13 21:22:39

你可以采取几种不同的方法。在最初的例子中,每一行都用不同的颜色来具体地着色。如果你能在你想要绘制的数据/颜色上循环,那就很好了。手动分配每种颜色,就像你现在所做的那样,是一项繁重的工作,即使是20行,但是想象一下,如果你有100多行。:)

Matplotlib还允许您使用自己的颜色编辑默认的“颜色周期”。考虑这个例子:

numlines = 10

data = np.random.randn(150, numlines).cumsum(axis=0)
plt.plot(data)

这将提供默认行为,并导致:

enter image description here

如果要使用默认Matplotlib colormap,可以使用它来检索颜色值。在

^{pr2}$

然后可以将颜色列表分配给Matplotlib中的color cycle设置。在

mpl.rcParams['axes.color_cycle'] = hex_colors

在这个循环之后,这些颜色将自动改变:

plt.plot(data)

enter image description here

相关问题 更多 >