2014-02-27 256 views
0

我有很多不同的文件(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

+0

您可能会发现有关这个问题/答案:用不同的颜色matplotlib绘制箭头( http://stackoverflow.com/questions/18748328/plotting-arrows-with-different-color-in-matplotlib) – Schorsch

回答

1

你可以采取几种不同的方法。在你最初的例子中,你用不同的颜色为每一行着色。如果你能够遍历你想要绘制的数据/颜色,那很好。像现在这样手动指定每种颜色,即使是20行,也要做很多工作,但想象一下,如果您有数百个或更多。 :)

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

numlines = 10 

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

这给出了默认的行为,并导致:如果你想使用默认Matplotlib颜色表

enter image description here

,你可以用它来获取颜色值。

# pick a cmap 
cmap = plt.cm.RdYlBu 

# get the colors 
# if you pass floats to a cmap, the range is from 0 to 1, 
# if you pass integer, the range is from 0 to 255 
rgba_colors = cmap(np.linspace(0,1,numlines)) 

# the colors need to be converted to hexadecimal format 
hex_colors = [mpl.colors.rgb2hex(item[:3]) for item in rgba_colors.tolist()] 

然后,您可以颜色列表分配到从Matplotlib的color cycle设置。

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

这种变化之后的任何情节会自动通过这些颜色周期:

plt.plot(data) 

enter image description here

+0

嗨Rutger,我遇到了麻烦:'hex_colors = [mpl.colors.rgb2hex(item [ :3])为rgba_colors.tolist()中的项目]'我得到一个错误消息e'of'hex_colors = [plt.colors.rgb2hex(item [:3])for item in rgba_colors.tolist()] AttributeError:'function'object has no attribute'rgb2hex''我不知道如何解决这个问题? – Kg123

+0

尝试像导入matplotlib:'import matplotlib as mpl'。 –