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

瘦欲@ 提交于 2021-01-28 11:28:06

问题


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.


回答1:


IDL v8 has an easy to use keyword for the PLOT function called VERT_COLORS:

; generate some sample data
x = cos(dindgen(100)/20)
y = sin(dindgen(100)/20)
z = dindgen(100)+100

; plot the data
p = plot(x, y, vert_colors=bytscl(z), rgb_table=39, xrange=[-2,2], yrange=[-2,2], thick=3, /aspect_ratio)
cb = colorbar(range=[min(z), max(z)], target=p)

The z data is scaled to a byte index of the colortable number 39. The colorbar needs to know the data range explicitly.




回答2:


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

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



来源:https://stackoverflow.com/questions/58903874/how-to-generate-the-lineared-color-plot-cplot-with-z-values-in-colorbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!