Python for Finance: Analyze Big Financial Data

(Elle) #1

Two-Dimensional Plotting


To begin with, we have to import the respective libraries. The main plotting functions are


found in the sublibrary matplotlib.pyplot:


In  [ 1 ]:  import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline

One-Dimensional Data Set


In all that follows, we will plot data stored in NumPy ndarray objects. However,


matplotlib is of course able to plot data stored in different Python formats, like list


objects, as well. First, we need data that we can plot. To this end, we generate 20 standard


normally distributed (pseudo)random numbers as a NumPy ndarray:


In  [ 2 ]:  np.random.seed( 1000 )
y = np.random.standard_normal( 20 )

The most fundamental, but nevertheless quite powerful, plotting function is plot from the


pyplot sublibrary. In principle, it needs two sets of numbers:


x values: a list or an array containing the x coordinates (values of the abscissa)


y values: a list or an array containing the y coordinates (values of the ordinate)


The number of x and y values provided must match, of course. Consider the following two


lines of code, whose output is presented in Figure 5-1:


In  [ 3 ]:  x   =   range(len(y))
plt.plot(x, y)

Figure 5-1. Plot given x and y values

plot notices when you pass an ndarray object. In this case, there is no need to provide the


“extra” information of the x values. If you only provide the y values, plot takes the index


values as the respective x values. Therefore, the following single line of code generates


exactly the same output (cf. Figure 5-2):


In  [ 4 ]:  plt.plot(y)
Free download pdf