根据他们拥有的属性绘制不同颜色的不同线条

时间:2016-04-13 07:09:56

标签: python matplotlib plot

我试图在2d表面上绘制一些具有不同方向的线条。 对于每一行,我根据我正在检查的属性在列表中有一个数字,所以如果我有两行共享该属性,那么它将具有相同的颜色。 我怎么做? 我所拥有的代码似乎并没有那样工作。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm


def line(x,y,ang):
    a=[]
    for i in range(len(ang)):
        a.append(np.deg2rad(ang[i]))
    Xmax=[]
    Ymax=[]
    Xmin=[]
    Ymin=[]
    L=100           
    for i in range(len(x)):
        Xmax.append(x[i]+L*np.sin(a[i]))
        Ymax.append(y[i]+L*np.cos(a[i]))
        Xmin.append(x[i]-L*np.sin(a[i]))
        Ymin.append(y[i]-L*np.cos(a[i]))
    X=[Xmin,Xmax]
    Y=[Ymin,Ymax]
    return X, Y



#my data for the lines
ang=[210,291,226,350,217,220,331]
lat=[32.7338,31.5918,32.2529,33.0827,30.1177,29.79329,32.6217]
lon=[35.1918,35.3933,35.526,35.1741,34.7257,34.9152,34.9862]



#the properties of the lines
rect=[0.899,0.845,0.97,0.4,0.48,0.65,0.77]



#the colors i want the lines to have
colors=('r-','g-','y-','m-','c-','b','k-')


#the center of the plot
av_lat=np.average(lat)
av_lon=np.average(lon)

#XX and YY are arrays that contain 2 points in each ax, for a given number of lines
XX,YY=line(lon,lat,ang)

#not important
rows=2
columns=2
xav=np.average(lon)
yav=np.average(lat)
xr=np.arange(xav-columns,xav+columns,0.01)
yr=np.arange(yav-rows,yav+rows,0.01)


####i am trying to give each line a color based on one of the propertys above
col=[]
R=max(rect)
for i in range(len(rect)):
    if rect[i]<=0.5:
        col.append(colors[0])
    elif rect[i]<=0.8:
        col.append(colors[1])
    elif rect[i]<=0.82:
        col.append(colors[2])
    elif rect[i]<=0.84:
        col.append(colors[3])
    elif rect[i]<=0.86:
        col.append(colors[4])
    elif rect[i]<=0.88:
        col.append(colors[5])
    else:
        col.append(colors[6])


plt.figure(1)
axes = plt.gca()
plt.plot(lon,lat,'ko')
axes.set_ylim([yr[0], yr[len(yr)-1]]) ; axes.set_xlim([xr[0], xr[len(xr)-1]])
plt.plot(XX,YY,c=col)  #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<how do i give the lines i have, a color based on propertys they have
#plt.savefig('lines.png')
plt.show()

1 个答案:

答案 0 :(得分:0)

在删除噪音和构建虚假数据后,您可以执行以下操作:

它取线的斜率并根据该斜率的符号和值指定颜色。当然,这有点人为,但重构条件的计算以及将颜色分配给代码的不同部分使得它易于理解,维护,修改和适应。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm

import random

def slope(x, y):
    return (y[0] - y[1]) / (x[0] - x[1])

def get_color(condition):
    if condition < 0:
        if abs(condition) < 1:
            return 'red'
        else:
            return 'green'
    else:
        if abs(condition) < 1:
            return 'blue'
        else: return 'cyan'

XX = [(random.random(), random.random()) for _ in range(12)]
YY = [(random.random(), random.random()) for _ in range(12)]


plt.figure(1)
for x, y in zip(XX, YY):
    color = get_color(slope(x, y))

    plt.plot(x ,y, linewidth=3, color=color)
plt.show()

在此示例中,绘制了12个线段;那些具有负斜率的是redgreen,最陡green;正斜率为bluecyan,最陡cyan

enter image description here