【问题标题】:Plotting a scatter plot in python where the z value corresponds to a color key在 python 中绘制散点图,其中 z 值对应于颜色键
【发布时间】:2018-01-31 14:47:38
【问题描述】:

我想绘制一个散点图,其中每个点的颜色对应于第三个数组的值。 颜色需要特定于称为颜色的键。 因此,如果 z 值为 4,则颜色应为 '#9C6BE1'

colors= ["#049FBB", "#5DF10A", "#BF5B3F", "#A95058", "#9C6BE1","#6CC43C","#7B3001", "#B3D407","#97CE66"] #hex colours

x = [1,2,3,4]
y = [3,4,8,6]
z= [4,6,8,2]

plt.scatter(x,y,c=c)

如何将每个点绘制成与 z 值对应的颜色?

【问题讨论】:

    标签: python matplotlib plot colors


    【解决方案1】:

    您可以尝试使用列表理解和列表索引

    colors= ["#049FBB", "#5DF10A", "#BF5B3F", "#A95058", "#9C6BE1","#6CC43C","#7B3001", "#B3D407","#97CE66"] #hex colours
    
    x = [1,2,3,4]
    y = [3,4,8,6]
    z= [4,6,8,2]
    
    plt.scatter(x,y,c=[colors[i] for i in z])
    

    【讨论】:

      【解决方案2】:

      试试这个:通过使用列表推导,您可以使用 z 中的值作为索引来创建具有所需颜色的列表。

      colors= ["#049FBB", "#5DF10A", "#BF5B3F", "#A95058", "#9C6BE1","#6CC43C","#7B3001", "#B3D407","#97CE66"] #hex colours
      
      x = [1,2,3,4]
      y = [3,4,8,6]
      z= [4,6,8,2]
      
      plt.scatter(x,y,c=[colors[index] for index in z])
      

      导致这张照片

      【讨论】:

      • 太好了,正是我需要的。
      猜你喜欢
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多