Python for Finance: Analyze Big Financial Data

(Elle) #1

Use of two subplots (upper/lower, left/right)


Let us first introduce a second y-axis into the plot. Figure 5-10 now has two different y-


axes. The left y-axis is for the first data set while the right y-axis is for the second.


Consequently, there are also two legends:


In  [ 13 ]: fig,    ax1 =   plt.subplots()
plt.plot(y[:, 0 ], ‘b’, lw=1.5, label=‘1st’)
plt.plot(y[:, 0 ], ‘ro’)
plt.grid(True)
plt.legend(loc= 8 )
plt.axis(‘tight’)
plt.xlabel(‘index’)
plt.ylabel(‘value 1st’)
plt.title(‘A Simple Plot’)
ax2 = ax1.twinx()
plt.plot(y[:, 1 ], ‘g’, lw=1.5, label=‘2nd’)
plt.plot(y[:, 1 ], ‘ro’)
plt.legend(loc= 0 )
plt.ylabel(‘value 2nd’)

Figure 5-10. Plot with two data sets and two y-axes

The key lines of code are those that help manage the axes. These are the ones that follow:


fig,    ax1 =   plt.subplots()
# plot first data set using first (left) axis
ax2 = ax1.twinx()
# plot second data set using second (right) axis

By using the plt.subplots function, we get direct access to the underlying plotting


objects (the figure, subplots, etc.). It allows us, for example, to generate a second subplot


that shares the x-axis with the first subplot. In Figure 5-10 we have, then, actually two


subplots that overlay each other.


Next, consider the case of two separate subplots. This option gives even more freedom to


handle the two data sets, as Figure 5-11 illustrates:


In  [ 14 ]: plt.figure(figsize=( 7 ,     5 ))
plt.subplot( 211 )
plt.plot(y[:, 0 ], lw=1.5, label=‘1st’)
plt.plot(y[:, 0 ], ‘ro’)
plt.grid(True)
plt.legend(loc= 0 )
plt.axis(‘tight’)
plt.ylabel(‘value’)
plt.title(‘A Simple Plot’)
plt.subplot( 212 )
plt.plot(y[:, 1 ], ‘g’, lw=1.5, label=‘2nd’)
plt.plot(y[:, 1 ], ‘ro’)
Free download pdf