import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
data = np.arange(10)
data
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
plt.plot(data)
[<matplotlib.lines.Line2D at 0x226505a9978>]
图片与子图
使用plt.figure生成一个新的图片
fig = plt.figure()
<Figure size 432x288 with 0 Axes>
add_subplot创建一个或多个子图(subplot)
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(np.random.randn(50).cumsum(),'k--')
_ = ax1.hist(np.random.randn(100),bins=20,color='k',alpha=0.3)
ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30))
<matplotlib.collections.PathCollection at 0x22652533c50>
s = pd.Series(np.random.randn(10),index=np.arange(0,100,10))
s
0 -0.216889
10 -0.926422
20 -1.578404
30 1.260680
40 0.765321
50 1.575562
60 -0.226129
70 -1.545994
80 1.461791
90 0.216152
dtype: float64
s.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x22652df9518>
df = pd.DataFrame(np.random.randn(10,4).cumsum(0),
index=np.arange(0,100,10),
columns=['A','B','C','D'])
df
A | B | C | D | |
---|---|---|---|---|
0 | 0.148623 | -0.464732 | 0.170983 | -1.931102 |
10 | 2.051717 | -0.547495 | 2.022106 | -1.521699 |
20 | 2.851331 | -1.703850 | 0.804570 | -1.245837 |
30 | 4.236059 | -0.807866 | 3.380667 | -0.467652 |
40 | 5.586521 | -1.819789 | 3.505844 | -0.112501 |
50 | 4.943688 | -0.578019 | 4.009679 | -1.821747 |
60 | 5.507788 | -1.172690 | 4.345803 | -4.397258 |
70 | 4.598429 | 0.147067 | 3.977140 | -4.439640 |
80 | 4.662817 | -0.275686 | 6.488330 | -2.747436 |
90 | 2.205290 | 0.145558 | 6.516990 | -3.706320 |
df.plot()
<matplotlib.axes._subplots.AxesSubplot at 0x22652e85d68>
# 柱状图
s.plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot at 0x22652efc390>
s.plot(kind='barh')
<matplotlib.axes._subplots.AxesSubplot at 0x22652f3ae80>
df.plot(kind='bar')
<matplotlib.axes._subplots.AxesSubplot at 0x22652fc05c0>
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
fig, ax = plt.subplots()
ax.plot(np.random.rand(20), '-o', ms=20, lw=2, alpha=0.7, mfc='blue')
ax.grid()
fig.text(0.95, 0.05, 'Property of MPL',
fontsize=50, color='gray',
ha='right', va='bottom', alpha=0.5)
plt.show()