matplotlib

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() 选项

参数说明
nrowssubplot的行数
ncolssubplot的列数
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

characterdescription
.point marker
,pixel marker
ocircle marker
vtriangle_down marker
^triangle_up marker
<triangle_left marker
>triangle_right marker
1tri_down marker
2tri_up marker
3tri_left marker
4tri_right marker
ssquare marker
ppentagon marker
*star marker
hhexagon1 marker
Hhexagon2 marker
+plus marker
xx marker
Ddiamond marker
dthin_diamond marker
|vline marker
_hline marker

在这里插入图片描述
在这里插入图片描述

Line Styles

characterdescription
-solid line style
--dashed line style
-.dash-dot line style
:dotted line style

Colors

color 还可以通过指定的 RGB 值的形式使用(#CECECE)

charactercolor
bblue
ggreen
rred
ccyan
mmagenta
yyellow
kblack
wwhite
plt.plot(randn(30).cumsum(),color='#CECECE')
#figure5

在这里插入图片描述

#ax.plot(x,y,linestyle='--',color='g')
plt.plot(randn(30).cumsum(),'o--k')
#figure6

在这里插入图片描述

drawstyle 选项

参数描述
defaultthe points are connected with straight lines
steps-preThe step is at beginning of the line segment
i.e. the line will be at the y-value of point to the right
steps-midThe step is halfway between the points
steps-postThe 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
stepsis 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()

annotate官网API

parametersdescriptions
textstr
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
arrowpropsdict, 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:]
cpim1tbilrateunemp
198-0.0079040.045361-0.3968810.105361
199-0.0219790.066753-2.2772670.139762
2000.0023400.0102860.6061360.160343
2010.0084190.037461-0.2006710.127339
2020.0088940.012202-0.4054650.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)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值