matplotlib绘图与可视化

  • 使用matplotlib:import matplotlib.pyplot as plt
  • 简单的线性图
import matplotlib.pyplot as plt
import numpy as np

date = np.arange(10)
plt.plot(date)
plt.show()

在这里插入图片描述

1.图片和子图

  • 一个带有三个子图的图片
#9.1图片与子图
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.show()
# plt.plot(np.random.randn(50).cumsum(),'k--')#'k--':用于回执黑色分段的style选项
# plt.show()

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))#散点图
ax3.plot(np.random.randn(50).cumsum(),'k--')#折线

plt.show()

在这里插入图片描述

#9.1.1.1调整子图周围的间距 subplots_adjust
fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)#wspace,hspace分别控制图片的宽度和高度的百分比,将子图之间的间距缩小到0
plt.show()

在这里插入图片描述

2.颜色、标记和线类型

#9.1.2颜色、标记和线类型
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(np.random.randn(30).cumsum(),'ko--')
plt.plot(np.random.randn(30).cumsum(),'g--')
plt.show()

在这里插入图片描述

fig = plt.figure()
date = np.random.randn(30).cumsum()
plt.plot(date,'k--',label='Default')
plt.plot(date,'k-',drawstyle='steps-post',label='steps-post')
plt.show()

在这里插入图片描述

3.刻度、标签和图例

#9.3刻度、标签和图例
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(np.random.randn(1000).cumsum())

ticks = ax.set_xticks([0,255,500,750,2000]) #数据范围内设定刻度的位置(x轴的刻度)
labels = ax.set_xticklabels(['one','two','three','four','fivr'],
                             rotation=30,fontsize='small')#为标签赋值

ax.set_title('My first matplotilob plot')#标题
ax.set_xlabel('Stages')#横坐标标签

'''
props={
    'title':'My first matplotilob plot'
    'xlabel':'Stages'
}
ax.set(**props)
'''
plt.show()

在这里插入图片描述

#9.1.3.2添加图例
from numpy.random import randn
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.plot(randn(1000).cumsum(),'k',label='one')
ax.plot(randn(1000).cumsum(),'k--',label='two')
ax.plot(randn(1000).cumsum(),'k.',label='three')


'''
ax.legend()或plt.legend():在图上标明一个图例,用于说明每条曲线的文字显示
取消图例中的元素,不要传入label参数或者传入label='_nolegend_'
'''
ax.legend(loc='best')#loc:用于控制图例的位置
plt.show()

在这里插入图片描述

4.注释和子图加工

#9.1.4注释与子图加工
'''
text、arrow、annote方法:添加注释和文本
text在表图上给定坐标(x,y),根据可选的定制样式绘制文本
ax.text(x,y,'Hello'',
    family='monospace',fontsize=10)
'''
#
# #绘制标普500指数从2007年以来的收盘价,并在图表中注释从20082009年金融危机的重要日期
# import pandas as pd
# from datetime import datetime
#
# fig = plt.figure()
# ax=fig.add_subplot(1,1,1)
#
# date = pd.read_csv('example/spx.csv',index_col=0,parse_dates=True)#读取数据
# spx = date['SPX']
#
# spx.plot(ax=ax,style='k--')
#
# crisis_date = [
#     (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_date:
#     ax.annotate(label,xy=(date,spx.asof(date)+75),
#                 xytext=(date,spx.asof(date)+75),
#                 arrowprops=dict(facecolor='black',headwidth=4,width=2,headlength=4),
#                 horizontalalignment='left',verticalalignment='top')#ax.annotate方法在指定的x,y坐标上绘制标签
#
# #放大2007年-2010
# '''
# ax.set_xlim和ax.set_ylim:手动绘制图表的边界
# '''
# ax.set_xlim(['1/1/2007','1/1/2011'])
# ax.set_ylim([600,1800])
#
# ax.set_title('Improtant dates in the 2008-2009 financial crisis')
#
# plt.show()

'''
常见的图形,matplotlib.pyplot 图形全集:matplotlib.patches
'''
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)

plt.show()

在这里插入图片描述

5.将图片保存到文件

#9.1.5将图片保存到文件
'''plt.savefig(fname,dpi,facecolor,edgecolor子图外的背景颜色,format文件格式,bbox_inches要保存的图片范围)'''

6.matplotlib设置

#9.1.6 matplotlib设置
'''
matplotlib设置:rc()
font_options={'family':'monospce',
              'weigth':'bold',
              'size':'small'}
plt.rc('font',**font_options)
'''

7.折线图

#9.2.2折线图
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#简单序列图形
'''
Series.plot(label,ax,style,alpha,kind,logy,use_index,rot,xticks,yticks,xlim,ylim,grid)
'''
s = pd.Series(np.random.randn(10).cumsum(), index=np.arange(0,100,10))
s.plot()
plt.show()

在这里插入图片描述

#简单DataFrame绘图
'''
DataFrame.plot(subplots将DateFramed的每一列绘制在独立的子图中,sharex,sharey,figsize,title,legend,sort_columns按字母顺序绘制各列)
'''
plt.figure()
df = pd.DataFrame(np.random.randn(10,4).cumsum(0),
                  columns=['A','B','C','D'],
                  index=np.arange(0,100,10))
df.plot()
plt.show()

在这里插入图片描述

8.柱状图

#9.2.2 柱状图
'''
plot.bar()和plot.barh()分别绘制垂直和水平的柱状图
'''
#水平柱状图和垂直柱状图
fig,axes = plt.subplots(2,1)
data = pd.Series(np.random.randn(16),index=list('abcdefghijklmnop'))
data.plot.bar(ax=axes[0],color='k',alpha=0.7)
data.plot.barh(ax=axes[1],color='k',alpha=0.7)
plt.show()

在这里插入图片描述

#DataFrame柱状图
df = pd.DataFrame(np.random.randn(6,4),
                  index=['one','two','three','four','fivr','six'],
                  columns=pd.Index(['A','B','C','D'],name='Genus'))
df.plot.bar()
plt.show()

在这里插入图片描述

df.plot.barh(stacked=True,alpha=0.6)#stacked=True生成推挤柱状图,使每一行的值堆积在一起
plt.show()

在这里插入图片描述

9.直方图和密度图

#9.2.3直方图和密度图
'''
直方图:plot.hist()
密度图:Plot.density()
'''

10.散点图或点图

11. 分面网格和分类数据

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w要变强

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值