简体   繁体   English

带有 matplotlib 的颜色图

[英]Colormap with matplotlib

I am trying to represent 3D scatter data with matplotlib.我试图用 matplotlib 代表 3D 散点数据。

I have 3 arrays to plot:我有 3 个 arrays 到 plot:

  • an array with X coordinates of points具有点 X 坐标的数组
  • an array with Y coordinates of points具有点的 Y 坐标的数组
  • an array with a parameter values linked with each point (points of which the coordinates are described in X[] and Y[]具有与每个点链接的参数值的数组(其坐标在 X[] 和 Y[] 中描述的点

What I would like to have is:我想要的是:

  • a 2D point cloud (scatter) plot for each (X,Y) couple每个(X,Y)对的二维点云(散点图)plot
  • each point has a color according to the corresponding value in the 3rd array根据第三个数组中的对应值,每个点都有一个颜色
  • a color bar representing the range and values of the linked parameter表示链接参数的范围和值的颜色条

I am having problems with the color mapping.我遇到了颜色映射问题。 Here is a minimal code with comments:这是带有注释的最小代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap

X = [] # x coordinates array
Y = [] # y coordinates array
parameter = [] # linked parameter values array, each value represents a point. This array is ordered accordingly

# next : the arrays are populated ..
# now I need to plot the point cloud (X,Y) with each point having a color representing the value of the corresponding linked parameter.. 

I've read some tutorials and understood that I need to create a customized colormap for the parameter.我已经阅读了一些教程并了解我需要为参数创建自定义颜色图。 I've tried to create a colormap according to the linked parameter by:我尝试通过以下方式根据链接参数创建颜色图:

viridisBig = cm.get_cmap('viridis', 512)
newcmp = ListedColormap(viridisBig(np.linspace(np.min(PARAMETER), np.max(PARAMETER), 512)))

Then called the scatter plot:然后调用散点plot:

plt.scatter(X, Y, cmap=newcmp)
plt.colorbar(cm.ScalarMappable(cmap=newcmp))
plt.show()

The above code is not working properly.上面的代码不能正常工作。 It is plotting the scatter plot with a unique color (blue) and the colorbar on the side is yellow, as in the attached screenshot:它正在绘制具有独特颜色(蓝色)的散点 plot 并且侧面的颜色条为黄色,如所附屏幕截图所示:

输出图

I guess I'm missing something related to the creation of the colormap, but I haven't found any clear examples for this simple case.我想我遗漏了一些与创建颜色图相关的东西,但我还没有找到任何关于这个简单案例的明确示例。 Any ideas?有任何想法吗?

Thanks in advance!提前致谢!

Problem solved by normalizing the parameter before using it with a colormap as parameters for the scatter function:通过在将颜色图用作散点图 function 的参数之前对参数进行归一化解决了问题:

colormap = plt.cm.get_cmap('cool', 512)
normalize = mpl.colors.Normalize(vmin=PARAMETER.min(), vmax=PARAMETER.max())

Then:然后:

plt.scatter(X, Y, c=PARAMETER, s=5, cmap=colormap, norm=normalize)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM