Skip to main content
 首页 » 编程设计

python之在 matplotlib 中用不同的颜色绘制 'vectors'

2025年05月04日12shanyou

我的数据是:

import matplotlib.pyplot as plt 
from datetime import * 
import matplotlib 
 
my_vectors =[['120819152800063',10,189, 8], 
 ['120819152800063', 10,184, 8], 
 ['120819152800063', 0,190, 43], 
 ['120819152800067', 8,67, 10], 
 ['120819152800067', 8,45, 10], 
 ['120819152800073', 10,31, 8], 
 ['120819152800073', 10,79, 8], 
 ['120819152800073', 7,102, 25], 
 ['120819152800075', 125,0, 13]] 

我试图绘制向量来表示数据,但我作弊了(我代表一条线,代表向量的主体,开始和结束有 2 个点),我只想给每个主体着色“向量”。

timeString = zip(*my_vectors)[0] 
timeDatetime=[datetime.strptime(aTime, '%y%m%d%H%M%S%f') for aTime in timeString] 
timeDate=matplotlib.dates.date2num(timeDatetime) 
# Represent the data time 
X = tuple([int(x) for x in timeString]) 
# Represent the data sender 
Y = zip(*my_vectors)[1] 
# represent the data type  
U = zip(*my_vectors)[2] 
# represent the data receiver 
V = zip(*my_vectors)[3] 
 
# the 'body' of the vectors 
plt.vlines(timeDate,Y,V,colors='r') 
# the beginning of the vectors 
plt.plot_date(timeDate,Y,'b.',xdate=True) 
# the end of the vectors 
plt.plot_date(timeDate,V,'y.') 
plt.show() 

为了更好地读取我的数据,我需要为每种数据类型更改颜色,但我不知道我将拥有多少种数据类型。 我该怎么做?

我读过这个问题,但我不太明白答案:

Setting different color for each series in scatter plot on matplotlib

请您参考如下方法:

您可以使用颜色图访问不同的颜色。模块matplotlib.cm提供颜色图,或者您可以 c reate your own . This demo显示可用的颜色图及其名称。颜色图包含 256 种不同的颜色。您可以遍历数据并为每个向量分配不同的颜色,就像您链接到的示例中所做的那样。如果您有超过 256 个数据点,您将需要重复颜色或使用更大的颜色图,但无论如何您都可能会遇到光谱分辨率的限制。

这是一个基于您的问题的示例。

from matplotlib import pyplot as plt 
import matplotlib.cm as cm 
import numpy as np 
 
# Some fake data 
timeDate = np.arange(256) 
Y = timeDate * 1.1 + 2 
V = timeDate * 3 + 1 
 
# Select the color map named rainbow 
cmap = cm.get_cmap(name='rainbow') 
 
# Plot each vector with a different color from the colormap.  
for ind, (t, y, v) in enumerate(zip(timeDate, Y, V)): 
    plt.vlines(t,y,v ,color = cmap(ind)) 
 
plt.show() 

或者,您可以直接从颜色图中访问 RGBA 值:

plt.vlines(timeDate,Y,V,colors=cmap(np.arange(256)))