import matplotlib.pyplot as plt
解决 fig.show() 不显示问题
pip install PyQt5
import matplotlib
print(matplotlib.get_backend())
matplotlib.use('Qt5Agg')
print(matplotlib.get_backend())
module://ipykernel.pylab.backend_inline
Qt5Agg
data = randn(30).cumsum()
data
array([-0.47038157, -2.54851864, -3.02072243, -3.26457657, -3.98861465,
-3.55895676, -3.09222843, -1.99577254, -4.63871866, -5.46383038,
-6.88051914, -6.63431456, -5.70190328, -5.56277675, -5.1221408 ,
-5.93428386, -6.66235474, -6.12002098, -6.98999279, -7.81181152,
-7.13399239, -7.77802499, -5.05254402, -5.78587831, -5.17780887,
-3.78129518, -4.22778456, -3.21633671, -4.17468374, -3.36660901])
fig = plt.figure()
fig.show()
k-- 是一个线型选项,告诉matplotlib绘制黑色虚线图
from numpy.random import randn
plt.plot(randn(50).cumsum(),'k--')
#figure1
from numpy.random import randn
import matplotlib.pyplot as plt
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--')
# figure2
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
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--')
_ = ax1.hist(randn(100),bins=20,color='k',alpha=0.3)
ax2.scatter(np.arange(30),np.arange(30) + 3*randn(30))
# figure3
pyplot.subplots() 选项
参数 | 说明 |
---|---|
nrows | subplot的行数 |
ncols | subplot的列数 |
sharex | 所有subplot应用使用相同的X轴刻度 (调节xlim将会影响所有subplot) |
sharey | 所有subplot应用使用相同的Y轴刻度 (调节ylim将会影响所有subplot) |
subplot_kw | 用于创建各subplot的关键字字典 |
**fig_kw | 创建figure时其他关键字, 例如:plt.subplots(2,2,figsize=(8,6)) |
调整subplot周围的间距
默认情况下,matplotlib会在subplot外围留下一定的边距,并在subplot之间留下一定的间距
subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None
wspace 和 hspace 用于控制宽度和高度的百分比,可以用作 subplot 之间的间距
fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
for j in range(2):
axes[i,j].hist(randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)
#figure4
plot.plot()
fmt = '[marker][line][color]'
Markers
character | description |
---|---|
. | point marker |
, | pixel marker |
o | circle marker |
v | triangle_down marker |
^ | triangle_up marker |
< | triangle_left marker |
> | triangle_right marker |
1 | tri_down marker |
2 | tri_up marker |
3 | tri_left marker |
4 | tri_right marker |
s | square marker |
p | pentagon marker |
* | star marker |
h | hexagon1 marker |
H | hexagon2 marker |
+ | plus marker |
x | x marker |
D | diamond marker |
d | thin_diamond marker |
| | vline marker |
_ | hline marker |
Line Styles
character | description |
---|---|
- | solid line style |
-- | dashed line style |
-. | dash-dot line style |
: | dotted line style |
Colors
color 还可以通过指定的 RGB 值的形式使用(#CECECE
)
character | color |
---|---|
b | blue |
g | green |
r | red |
c | cyan |
m | magenta |
y | yellow |
k | black |
w | white |
plt.plot(randn(30).cumsum(),color='#CECECE')
#figure5
#ax.plot(x,y,linestyle='--',color='g')
plt.plot(randn(30).cumsum(),'o--k')
#figure6
drawstyle 选项
参数 | 描述 |
---|---|
default | the points are connected with straight lines |
steps-pre | The step is at beginning of the line segment i.e. the line will be at the y-value of point to the right |
steps-mid | The step is halfway between the points |
steps-post | The step is at the end of the line segment i.e. the line will be at the v-value of the point to the left |
steps | is equal to ‘steps-pre’ and is maintained for backward-compatiblity |
plt.plot(randn(30),drawstyle='steps-post')
#figure7
data = randn(30).cumsum()
plt.plot(data,'k--',label='Default')
plt.plot(data,'k-',drawstyle='steps-post',label='steps-post')
#figure8
标题
set_title() 设置一个标题
修改 X轴刻度
set_xticks()
告诉matplotlib 要将刻度放在数据范围中的哪些位置,默认情况下,这些位置也就是刻度标签
set_xticklabels()
将任何其他的值作为标签
Y轴的修改方式与此类似
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())
ticks = ax.set_xticks([0,250,500,750,1000])
labels = ax.set_xticklabels(['one','two','three','four','five'])
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')
# figure9
Text(0.5, 0, 'Stages')
图例
ax.legend()
或 plt.legend()
自动创建图例
loc选项 | 描述 |
---|---|
best | 会选择最不碍事的地方 |
upper right | |
upper left | |
lower left | |
lower right | |
right | |
center left | |
center right | |
lower center | |
upper center | |
center |
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(),'k',label='one')
ax.plot(randn(1000).cumsum(),'g--',label='two')
ax.plot(randn(1000).cumsum(),'r.',label='three')
ax.legend(loc='best')
#figure10
要从图例中去除一个或多个元素,不传入label
或 传入 label='_nolegend_'
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(),'k')
ax.plot(randn(1000).cumsum(),'g--',label='_nolegend_')
ax.plot(randn(1000).cumsum(),'r.',label='three')
ax.plot(randn(1000).cumsum(),'b:',label='four')
ax.legend(loc='best')
#figure11
注解 matplotlib.pyplot.annotate()
parameters | descriptions |
---|---|
text | str The text of the annotation. s is a deprecated synonym for this parameter |
xy | (float,float) The point(x,y) to annotate |
xytext | (float,float),optional The position(x,y) to place the text at. If None,defaults to xy |
arrowprops | dict, optional The properties use to draw a FancyArrowPatch arrow between the positions xy and xytext |
import pandas as pd
from datetime import datetime
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
# 读入数据
data = pd.read_csv('files/spx.csv',index_col=0,parse_dates=True)
spx = data['SPX']
spx.plot(ax=ax,style='k-')
crisis_data = [
(datetime(2007,10,11),'Peak of bull market'),
(datetime(2008,3,12),'Bear Stearns Fails'),
(datetime(2008,9,15),'Lehman Bankruptcy')
]
for date,label in crisis_data:
ax.annotate(label,xy=(date,spx.asof(date)+50),
xytext=(date,spx.asof(date)+200),
arrowprops=dict(facecolor='black'),
horizontalalignment='left',verticalalignment='top')
# 放大到2007-2010
ax.set_xlim(['1/1/2007','1/1/2011'])
ax.set_ylim([600,1800])
ax.set_title('Important dates in 2008-2009 financial crisis')
#figure12
Text(0.5, 1.0, 'Important dates in 2008-2009 financial crisis')
部分内容解析
spx
1990-02-01 328.79
1990-02-02 330.92
1990-02-05 331.85
1990-02-06 329.66
1990-02-07 333.75
...
2011-10-10 1194.89
2011-10-11 1195.54
2011-10-12 1207.25
2011-10-13 1203.66
2011-10-14 1224.58
Name: SPX, Length: 5472, dtype: float64
print(type(spx))
<class 'pandas.core.series.Series'>
for date,label in crisis_data:
print(spx.asof(date))
print("+50 " + str(spx.asof(date)+50) + '\n')
1554.41
+50 1604.41
1308.77
+50 1358.77
1192.7
+50 1242.7
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
rect = plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.3)
circ = plt.Circle((0.7,0.2),0.15,color='b',alpha=0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color='g',alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
#figure13
pandas 绘图
Series.plot()
DataFrame.plot()
线型图
from pandas import Series
s = Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s.plot()
#figure14
from pandas import DataFrame
df = DataFrame(np.random.randn(10,4).cumsum(0),
columns=['A','B','C','D'],
index=np.arange(0,100,10))
df.plot()
#figure15
柱状图
fig, axes = plt.subplots(2,1)
data = Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar',ax=axes[0],color='b',alpha=0.7)
data.plot(kind='barh',ax=axes[1],color='g',alpha=0.7)
#figure16
df = DataFrame(np.random.rand(6,4),index=['one','two','three','four','five','six'],
columns=pd.Index(['A','B','C','D'],name='Genus'))
#‘Genus' 被用作图例的标题
df.plot(kind='bar')
#figure17
堆积柱状图
stacked=True
即可为DataFrame生成堆积柱状图
df.plot(kind='barh',stacked=True,alpha=0.5)
#figure18
频率柱状图
s = Series([4,4,4,7,2,1,1,2,9,8,8,1])
s.value_counts().plot(kind='bar')
#figure19
直方图
import pandas as pd
tips = pd.read_csv('files/tips.csv')
tips['tip_pct'] = tips['tip']/tips['total_bill']
tips['tip_pct'].hist(bins=50)
密度图 (kind=‘kde’)
Kernel Density Estimate 核密度估计
tips['tip_pct'].plot(kind='kde')
import numpy as np
from pandas import Series
comp1 = np.random.normal(0,1,size=200)
comp2 = np.random.normal(10,2,size=200)
values = Series(np.concatenate([comp1,comp2]))
values.hist(bins=100,alpha=0.3,color='k',normed=True)
values.plot(kind='kde',style='g--')
散布图
macro = pd.read_csv('files/macrodata.csv')
data = macro[['cpi','m1','tbilrate','unemp']]
trans_data = np.log(data).diff().dropna()
trans_data[-5:]
cpi | m1 | tbilrate | unemp | |
---|---|---|---|---|
198 | -0.007904 | 0.045361 | -0.396881 | 0.105361 |
199 | -0.021979 | 0.066753 | -2.277267 | 0.139762 |
200 | 0.002340 | 0.010286 | 0.606136 | 0.160343 |
201 | 0.008419 | 0.037461 | -0.200671 | 0.127339 |
202 | 0.008894 | 0.012202 | -0.405465 | 0.042560 |
import matplotlib.pyplot as plt
plt.title('Changes in log %s vs. log %s' %('m1','unemp'))
plt.scatter(trans_data['m1'],trans_data['unemp'])
from pandas.plotting import scatter_matrix
scatter_matrix(trans_data,diagonal='kde',color='r',alpha=0.3)