Here is the second lesson in Financial Computing and Programming
What I'm learning today is matplotlib - the most basic drawing library in python.
import matplotlib.pyplot as plt import numpy as np
1. We first generate a one-dimensional y (to draw a line chart)
Just draw a picture
np.random.seed(250) y = np.random.standard_normal(20) x = range(len(y)) plt.plot(x,y)
This is the same as the result of direct plt.plot(y)
2. Let's try the cumsum function initially
#add canvas here plt.figure(figsize = [7,4]) #This is used to draw straight lines plt.plot(y.cumsum() , "C1" , lw =1.2) #here to draw plt.plot(y.cumsum() , "ro") #This is used to add gridlines plt.grid("True") #Here is used to add x-axis and y-axis plt.xlabel("index") plt.ylabel("value") #Here is used to add a title plt.title("A simple plot")
For the cumsum function, axis=1 refers to the operation on the column (but it is not clear whether other axes will mean the same thing?)
You can see that the first column is unchanged
#For the cumsum function, axis=0 refers to operating on rows
You can see that the first line is unchanged.
3. Next we generate a two-dimensional y (to draw a line chart)
y = np.random.standard_normal((20,2)) y
plt.plot(y[:,0] , lw =1.2 , label = "1st") plt.plot(y[:,1] , lw = 1.2 , label = '2nd') plt.plot(y,"ro") plt.grid("True") plt.legend(loc = 0 ) # It is set to 0 here, which means the best match plt.xlabel("index") plt.ylabel("value") plt.title("This is my second picture") #The following is the function used to store, you can use the parameter dpi, such as =200 to specify the storage resolution plt.savefig("this_is_my_second_picture.png",dpi = 200)
Here is a description of the loc parameter
3. Next, we will y[:,0] = y[:,0] * 100 (what should we do if we encounter pictures with too large scale difference?)
plt.plot(y)
#If you encounter such a large-scale thing, you cannot place it in a picture.
We consider implementing the idea of "subgraph"
plt.subplot(nrows, ncols, index, **kwargs) plt.figure(figsize = (7,4)) plt.subplot(211)#The number here means 2 rows, 1 column, and the serial number is 1 plt.plot(y[:,0] , lw = 1.2 , label = "1st") plt.plot(y,"ro") plt.grid("True") plt.legend(loc = 0 ) # It is set to 0 here, which means the best match plt.xlabel("index") plt.ylabel("value") plt.subplot(212)#The number here means 2 rows, 1 column, and the serial number is 2 plt.plot(y[:,1] , lw = 1.2 , label = "1st") plt.plot(y,"ro") plt.grid("True") plt.legend(loc = 0 ) # It is set to 0 here, which means the best match plt.xlabel("index_2") plt.ylabel("value_2")
plt.figure(figsize = (7,4)) plt.subplot(121)#The number here means 1 row, 2 columns, and the serial number is 1 plt.plot(y[:,0] , lw = 1.2 , label = "1st") plt.plot(y,"ro") plt.grid("True") plt.legend(loc = 0 ) # It is set to 0 here, which means the best match plt.xlabel("index") plt.ylabel("value") plt.subplot(122)#The number here means 1 row, 2 columns, and the serial number is 2 plt.plot(y[:,1] , lw = 1.2 , label = "1st") plt.plot(y,"ro") plt.grid("True") plt.legend(loc = 0 ) # It is set to 0 here, which means the best match plt.xlabel("index_2") plt.ylabel("value_2")
Let's take a look at the statement used to draw the bar
plt.figure(figsize = (7,4))
4. Draw a double-axis graph in an object-oriented way (more recommended)
fig, ax = plt.subplots(nrows = 1 , ncols = 2) # nrows means rows # ncols for columns ax[0].plot([1,2,3],[4,5,6]) ax[1].scatter([1,2,3],[4,5,6]) ax[0].set_xlabel("index-1") ax[1].set_xlabel("index-2") ax[0].set_title("line") ax[1].set_title("scatter")
For the above scales that are too different, if we want to place them in one picture, we can consider using a dual-axis graph
The main use here is
ax2 = ax1.twinx()
Equivalent to overlaying two pictures on top of each other
fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twinx() ax1.plot(y[:,0] , lw =1.2,color = 'g' , label = "1st") ax1.plot(y[:,0],"ro") ax1.grid("True") ax1.legend(loc = 0 ) # It is set to 0 here, which seems to mean the best match. ax1.set_xlabel("index") ax1.set_ylabel("value") ax2.plot(y[:,1] , lw =1.2,color = 'b' , label = "2nd") ax2.plot(y[:,1],"ro") ax2.grid("True") ax2.legend(loc = 0 ) # It is set to 0 here, which seems to mean the best match. ax2.set_xlabel("index") ax2.set_ylabel("value")
5. Further improvements (legend s overlap each other?)
We found that our legend s overlapped with each other, only one. So let's solve this problem
fig = plt.figure() #here are axes ax1 = fig.add_subplot(111) ax2 = ax1.twinx() lne1 = ax1.plot(y[:,0] , lw = 1.2 , color = "b" , label = "1st") ax1.plot(y[:,0] , "ro") ax1.grid() ax1.set_xlabel("index") ax1.set_ylabel("this_is_the_values") ax1.set_title("this is some ?")
# ax1.legend(loc = 2) lne2 = ax2.plot(y[:,1] , lw = 1.2 , color = "C6" , label = "2nd") ax2.set_ylabel("vlaue_2") # ax2.legend(loc = 1) # #add Our line lns = lne1 + lne2 labs = [l.get_label() for l in lns] print(lns) print(labs) ax2.legend(lns,labs,loc= 9)
6. draw bar
plt.bar(x = np.arange(len(y)) , height = y[:,1]) plt.grid("True") plt.legend(loc = 0 ) # It is set to 0 here, which seems to mean the best match. plt.xlabel("index") plt.ylabel("value")
7. Here is the scatter plot:
data = np.random.standard_normal((20,2)) plt.figure(figsize = (8,4)) plt.scatter(data[:,0] , data[:,1] , marker = 'o' , color = "C6") plt.xlabel('x') plt.ylabel("y") plt.grid() plt.title("Here is the scatter plot")
We further refine it
The c here represents the "frequency" of this two-dimensional point
c = np.random.randint(0,10, len(y)) c
plt.figure(figsize = (7,4)) plt.scatter(data[:,0] , data[:,1] , c = c , marker = "o") plt.colorbar() plt.xlabel('x') plt.ylabel("y") plt.grid() plt.title("Here is a better looking scatter plot")
8. Histogram
plt.figure(figsize = (7,19)) plt.hist(data,label=["1st" , "2nd"] , bins = 10)
9. Box diagram
plt.boxplot(data)
10. Now let's draw a graph of a quadratic function!
def f(x): return x**2 - x*2 x = np.linspace(0,2) y=f(x) fig,ax = plt.subplots() plt.plot(x,y)
11.3D data mapping
strike = np.linspace(50,150,24) ttm = np.linspace(0.5,2.5,24) strike1,ttm1 = np.meshgrid(strike ,ttm) #numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None) returns evenly spaced numbers within the specified interval. inv = strike1 * ttm1 from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize = (14,7)) # This is used to control the size of the entire image ax= fig.gca(projection = "3d") surf = ax.plot_surface(strike1 , ttm1 , inv , rstride = 2 , cstride = 2,cmap = plt.cm.coolwarm , linewidth = 3) ax.set_xlabel("strike") ax.set_ylabel("ttm1") ax.set_zlabel("inv") fig.colorbar(surf , shrink = 0.5 , aspect =5) # The following parameters here are used to adjust the size of the column next to it plt.savefig("this.png" ,dpi = 200 )