简体   繁体   English

Matplotlib 自定义colors散plot

[英]Matplotlib custom colors in scatter plot

I would like to know if there is some elegant way to set discrete colors in a scatter plot based on the value of the entry.我想知道是否有一些优雅的方法可以根据条目的值在散点 plot 中设置离散 colors。 For a completly simplified example:对于一个完全简化的例子:

x=np.arange(100)
plt.scatter(x,x,c=x,cmap='jet')
plt.show()

在此处输入图像描述

So let's say I want all values lower than 40 green, those between 40 and 60 green, and those larger than 60 to be red.因此,假设我希望所有低于 40 绿色的值、介于 40 和 60 绿色之间的值以及大于 60 的值都为红色。 I know that I could create a loop with some if statements that generates a list based on those conditions, so that I have something like colorlist=['blue','blue',.....] .我知道我可以用一些 if 语句创建一个循环,这些语句根据这些条件生成一个列表,这样我就有了类似colorlist=['blue','blue',.....]东西。

在此处输入图像描述
I know that this works, but is there some different way of doing it, or is this the easiest way?我知道这行得通,但是是否有一些不同的方法,或者这是最简单的方法?

You can do something like this:你可以这样做:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as mcol

cmap = mcol.ListedColormap(["blue","green","red"])

bounds = [0, 40, 60, 100]
norm = mcol.BoundaryNorm(bounds, cmap.N)

x=np.arange(100)
plt.scatter(x,x,c=x,cmap=cmap,norm=norm)
plt.show()

在此处输入图像描述

For further details, take a look here :有关详细信息,请查看此处

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

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