Search code examples
pythonmatplotlibscipy

How can I setup the Matplotlib chart background to chromatic green and the line to chromatic red?


How can I setup the Matplotlib chart background to chromatic green and the line to chromatic red?

import numpy as np
import matplotlib.pyplot as plt
import scipy as sp 
from scipy import stats 
import numpy.random as rnd
import scipy.stats as sts
M = 365
dt=1/M
r = 0.2
sigma = 0.15
sdt =sigma*np.sqrt(dt)
S0 = 100

def N011(VA1, VA2) : 
    N01=np.sqrt(-2.*np.log(1-VA1))*np.cos(2*np.pi*VA2) 
    return N01

SLIST = []
SLIST.append(S0)
for i in range(0,M-1):
    VA11 = rnd.random()
    VA22 = rnd.random()
    while ((VA11 == 0.) | (VA11 == 1.)):
        VA11 = rnd.random()
    while ((VA22 == 0.) | (VA22 == 1.)):
        VA22 = rnd.random()
    N01 =N011(VA11, VA22)
    SLIST.append(SLIST[i]*(1.+N01*sdt+r*dt))

tlist = np.linspace(0,365, num = 365)    

plt.figure(num=0,dpi = 120)
plt.plot(tlist, SLIST)
plt.show()

FinancialStockSimulation


Solution

  • You can set the background and line color by adjusting your plot generation code as follows:

    plt.figure(num=0,dpi = 120)
    plt.plot(tlist, SLIST, color=(1, 0, 0))  # `color` is the line color
    ax = plt.gca()
    ax.set_facecolor((0, 1, 0))  # to set the background
    plt.show()
    

    The arguments are the (red, green, blue) components of the color you want. You can choose from other ways of specifying colors, if you wish.

    I found the answer to the background color question in this stack overflow post, and information about changing the line color is available in the matplotlib.pyplot.plot documentation. (You could also set the line color by retrieving the appropriate line artist from ax and using its set_color method, e.g. ax.get_children()[0].set_color((1, 0, 0)), but that is more complicated.)