简体   繁体   中英

How to use a float to specify a colour (not grayscale shades)?

Here is an example toy code to plot with colours having string numbers.

import numpy as np; import matplotlib.pyplot as plt;
c1=str(np.random.rand());c2=str(np.random.rand())
x1=[2,3,4];y1=[20,30,40];
x2=[-2,-3,-4];y2=[-20,-30,-40]
plt.plot(x1,y1,'*',c=c1)
plt.plot(x2,y2,'o',c=c2)

这就是颜色的样子

I want to ask, if there is a way to make the colours beyond gray shades, using a single number string?

You can either specify a RGB(A) color from providing a float 3-tuple (or 4-tuple), or you can pick a color from a colormap using a single float value:

from matplotlib import pyplot as plt
import numpy as np

x1 = [2, 3, 4]
y1 = [20, 30, 40]
x2 = [-2, -3, -4]
y2 = [-20,-30,-40]

plt.figure(1, figsize=(9, 4))

# Specify a RGB color from float 3-tuple
plt.subplot(1, 2, 1)
plt.plot(x1, y1, '*', c=np.random.rand(3))
plt.plot(x2, y2, 'o', c=np.random.rand(3))
plt.ylabel('RGB color from float 3-tuple')

# Specify a color from a colormap from a single float
plt.subplot(1, 2, 2)
plt.plot(x1, y1, '*', c=plt.cm.viridis(np.random.rand()))
plt.plot(x2, y2, 'o', c=plt.cm.viridis(np.random.rand()))
plt.ylabel('Color from colormap from single float')

plt.tight_layout()
plt.show()

输出量

Hope that helps!

Try replacing the lines

plt.plot(x1,y1,'*',c=c1)
plt.plot(x2,y2,'o',c=c2)

with

dots1 = plt.plot(x1,y1,'*',c=c1,label='x1')
dots2 = plt.plot(x2,y2,'o',c=c2,label='x2')
plt.setp(dots1, color='r', linewidth=2.0)
plt.setp(dots2, color='g', linewidth=2.0)

plt.legend()
plt.show()

图片

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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