Home > database >  How to define a color in matplotlib with combination of different percentage of different colors?
How to define a color in matplotlib with combination of different percentage of different colors?

Time:02-23

I have a series of data and for each of them, I would like to plot a line with matplotlib. And I want to define a color for each condition by a combination of two different colors in order to distinguish them but with gradually changing colors. For example, I would like to define a color like m% * blue n% * red, where m and n could be 10%, 20%, 30%, etc., something like the way to define a customized color in LaTex, but I could not find anything by search on the manual or internet. Could you please tell me how to do that?

My original data is large, in order to keep the question simple, I guess maybe I could use the following data as a minimum example. For example, the first line is in color 20%*blue 20 %*red and the second line could be in color 50%*blue 40 %*red or any combinations are good. I think the main aspect of the problem is kept.

import numpy as np
import matplotlib.pyplot as plt;

x1 = np.linspace(1, 10, 10)
y1 = np.random.rand(10)
x2 = np.linspace(1, 10, 20)
y2 = np.random.rand(20)

plt.plot(x1, y1)
plt.plot(x2, y2)

CodePudding user response:

You can pass to plt.plot function a parameter color as rgb value as color=(r,g,b), where r, g, b are float in [0,1] representing the percentage of red, green and blue. I wrote some example code:

def myfunction(x, a=1):
    return np.sin(x a)

x = np.linspace(-10,10,101)
plt.figure(figsize=(10,5))
for a in np.linspace(0,2,21):
    plt.plot(x, myfunction(x,a), color=(a/2, 1-a/2,0))
plt.show()

output:

enter image description here

in this example i use the parameter a to change the red and green color of the plot.

CodePudding user response:

Color mixing is non-trivial, even if we extract the RGBA values of enter image description here

  • Related