In [2]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
In [3]:
fig = plt.figure()
#if ipython --pylab was used in terminal, a new windows will show up
We can number scheme in matplotlib as that in MATLB using plt.figure(2). Through plt.gcf(), we can get a reference to the active figure.
We cannot make a plot without subplots. Hence, we need create one more subplot by add_subplot:
In [4]:
ax1 = fig.add_subplot(2,2,1)
It means that the figure should be 2 * 2, and we're selecting the first of 4 subplots (numbered from 1). If you create the next two subplots, you'll und up with a figure that looks like the figure as shown below
In [5]:
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
In [6]:
from numpy.random import randn
plt.plot(randn(50).cumsum(), 'k--')
#fig.show()
Out[6]:
In [7]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
plt.plot(randn(50).cumsum(), 'k--')
Out[7]:
In [15]:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
plt.plot(randn(50).cumsum(), 'o-', color='red')
# The objects returned by subplot are AxesSubplot, hence we can use it by calling each one’s instance methods
# _ = ax1.hist(randn(100), bins = 20, color = 'k', alpha = 0.3)
ax1.hist(randn(100), bins = 20, color = 'k', alpha = 0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3*randn(30))
Out[15]:
In [ ]:
In [ ]:
In [29]:
randn(3)
Out[29]:
In [30]:
np.arange(3)
Out[30]:
Since creating Figure and subplot is a very common task, hence a easier command 'plt.subplots' can be used to create a new Figure, and returns a NumPy array containing the created subplot objects:
In [29]:
fig, axes = plt.subplots(nrows=2,ncols=3, sharex=True, sharey=True) #sharex=True, sharey=True在比较相同范围数据时,非常有用
#for short, we can write as
# fig, axes = plt.subplots(2,3, sharex=True, sharey=True)
axes[0,0].hist(randn(100), bins=20, color = 'b', alpha = 0.8)
axes[1,1].hist(randn(100), bins =20, color = 'k', alpha = 0.4)
plt.subplots_adjust(wspace=0.2,hspace=0.2) # plt.subplots_adjust is used to adjust the spacing between the subfigures
plt.show()
In [23]:
In [ ]:
Table pyplot.subplots optins
arguments | descriptions |
---|---|
nrows | number of rows of subplots |
ncols | number of columns of subplots |
sharex or sharey | all subplots should use the same x-axis ticks |
subplot_kw | Dictionary of keywords for creating |
**fig_kw | additional keywords to subplots are used when creating the figure, such as plt.subplots(2,2, figsize=(8,6)) |
In [60]:
# For the reference of the default color map of matplotlib, see
# https://matplotlib.org/users/dflt_style_changes.html
# This example is from CHAPTER 3 of the book "
# matplotlib for developpers",
# but I made many revisions
import matplotlib.style
import matplotlib as mpl
mpl.style.use('classic')
mpl.rcParams['figure.facecolor'] = '1'
#if choose the grey backgroud, use 0.75
mpl.rcParams['figure.figsize'] = [6.4,4.8]
mpl.rcParams['lines.linewidth'] = 1.5
mpl.rcParams['legend.fancybox'] = True
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(1000)
y = np.random.randn(1000)
size=abs(50*x)
color=np.random.rand(1000)
plt.scatter(x, y, s=size, c=color)
plt.legend('x')
plt.grid()
plt.show()
In [67]:
import numpy as np
print(np.random.randn(40))
print(np.random.rand(40))
#here, we can observe some difference, because rand() functions
# in the range of [0,1]
In [19]:
import matplotlib.style
import matplotlib as mpl
mpl.style.use('classic')
mpl.rcParams['figure.facecolor'] = '1'
#if choose the grey backgroud, use 0.75
mpl.rcParams['figure.figsize'] = [6.4,4.8]
mpl.rcParams['lines.linewidth'] = 2.
#mpl.rcParams['legend.fancybox'] = True
mpl.rcParams['axes.linewidth'] = 1.5 #set the value globally
fig = plt.figure()
ax = fig.add_subplot(111)
import matplotlib.pyplot as plt
ax.plot([1,3,2,4],label='line')
ax.set_title('A domo function')
ax.legend(shadow=False, fancybox=True, framealpha=0.5)
ax.text(1.0,3.5, 'artificial function', family=['Serif'], fontsize=12)
ax.text(1.0,1.5, 'artificial function', family=['Arial'], fontsize=12)
#See https://matplotlib.org/users/recipes.html to find more
# details on the legend: transparancey, title
plt.show()
Polar plots use a compeletely different coordinate system, so we have dedicated a separate section to them.
For all the previous images, we used the Cartesian system--two perpendicular lines meet at a point (the origin of axes) with precise axies directions to determine positive and negative values on both, the X and Y axes.
A polar system is a 2D coordinate system, in which the position of a point is expressed in terms of a radius and an angle. This system is used where the relation between two points is better expressed using those information.
legend中可以既包含文本也可以包含箭头。现在我们以金融数据为例,来做一些实际演练。
In [33]:
from datetime import datetime
import pandas as pd
fig = plt.figure()
ax = fig.add_subplot(111)
data = pd.read_csv('pydata-book/ch08/spx.csv', index_col = 0, parse_dates=True)
spx = data['SPX']
spx.plot(ax=ax, style='k-')
Out[33]:
In [31]:
data
Out[31]:
In [ ]: