Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate the lineared color plot (cplot) with z values in colorbar

In MATLAB™ one can use cplot.m which can generate colored plot basically looks like 2d plot with 3rd axis (z-axis) value as colorbar. Is there any tool/plotting technique I can use to generate a similar plot in Python or IDL Programming Language?. The previous question on stack overflow dealing with different problem as given in a link.

cplot image (Linear colored line plot

like image 743
Pavan Avatar asked Dec 04 '25 18:12

Pavan


1 Answers

Matplotlib has not a cplot direct equivalent but you can use a LineCollection.

With this understanding you have to modify the usual boilerplate adding a specific import

In [1]: import numpy as np 
   ...: import matplotlib.pyplot as plt 
   ...: from matplotlib.collections import LineCollection                                 

Now, generate some data (c is the 3rd value associated with the (x, y) point)

In [2]: x = np.linspace(0, 6.3, 64) 
   ...: y = np.sin(x) ; c = np.cos(x)                                                     

LineCollection needs a 3D array, i.e. a list of segments, each segment a list of points, each point a list of coordinates, that we build using this recipe

In [3]: points = np.array([x, y]).T.reshape(-1,1,2) 
   ...: segments = np.concatenate([points[:-1], points[1:]], axis=1)   

Now we instantiate the LineCollection, specifying the colormap that we want and the line width, and immediately after we tell to our instance that its array (what is mapped to colors) is the array c

In [4]: lc = LineCollection(segments, cmap='plasma', linewidth=3) 
   ...: lc.set_array(c)                                                                   

and eventually we plot lc in its own way, call autoscale because it's needed (try not to call it...) and add a colorbar.

In [5]: fig, ax = plt.subplots()                                                          
   ...: ax.add_collection(lc) 
   ...: ax.autoscale() 
   ...: plt.colorbar(lc);

enter image description here

I know, it's a bit clunky but it works.

like image 159
gboffi Avatar answered Dec 06 '25 07:12

gboffi