Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

python - gnuplot linecolor variable in matplotlib?

I have an array of y-values that form a line. Additionally, I have an array with the same number of elements as the y-array of values ranging from 0 to 1. We'll call this array 'z'. I want to plot the array of y-values so that the color of each point corresponds with the z-value.

In gnuplot, you can do this using the 'lc variable':

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

Using the advice from here: Matplotlib scatterplot; colour as a function of a third variable , I was able to use a scatter plot, which did work:

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()  

Is there a way to do this with the plot method in matplotlib, similar to this?

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

When I tried the above code, all of the lines just appeared black.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same problem: wanted to plot line(s) with non-uniform color, which I wanted to be dependent on a third variable (z).

But I definitelly wanted to use a line, not markers (as in @joaquin's answer). I found a solution in a matplotlib gallery example, using the class matplotlib.collections.LineCollection (link here).

Here is my example, which plots trajectories in a Basemap, coloring them according to its height:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...