matplotlib是我们经常会用到的一款python绘图库,操作简单,几行代码就能很轻松地画一些或简单或复杂地图形,线图、直方图、功率谱、条形图、错误图、散点图以及费笛卡尔坐标图等都不在话下。今天小编就具体给大家介绍一下matplotlib绘图教程。
一、首先来了解一下matplotlib
1.matplotlib是基于python语言的开源数据绘图包。matplotlib的对象体系严谨而有趣,为我们提供了巨大的发挥空间。在熟悉了核心对象之后,我们可以轻易的定制图像。matplotlib使用numpy进行数组运算,并调用一系列其他的python库来实现硬件交互。
2.matplotlib安装
pip install matplotlib
3.Matplotlib导入
import matplotlib.pyplot as plt#为方便简介为plt
import numpy as np#画图过程中会使用numpy
import pandas as pd#画图过程中会使用pandas
二、matplotlib绘图
1.柱形图,散点图,饼状图,折线图
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure(figsize=(10,8)) #建立一个大小为10*8的画板
ax1 = fig.add_subplot(331) #在画板上添加3*3个画布,位置是第1个
ax2 = fig.add_subplot(3,3,2)
ax3 = fig.add_subplot(3,3,3)
ax4 = fig.add_subplot(334)
ax5 = fig.add_subplot(3,3,5)
ax6 = fig.add_subplot(3,3,6)
ax7 = fig.add_subplot(3,3,7)
ax8 = fig.add_subplot(3,3,8)
ax9 = fig.add_subplot(3,3,9)
ax1.plot(np.random.randn(10))
_ = ax2.scatter(np.random.randn(10),np.arange(10),color='r') #作散点图
ax3.hist(np.random.randn(20),bins=10,alpha=0.3) #作柱形图
ax4.bar(np.arange(10),np.random.randn(10)) #做直方图
ax5.pie(np.random.randint(1,15,5),explode=[0,0,0.2,0,0]) #作饼形图
x = np.arange(10)
y = np.random.randn(10)
ax6.plot(x,y,color='green')
ax6.bar(x,y,color='k')
data = DataFrame(np.random.randn(1000,10),
columns=['one','two','three','four','five','six','seven','eight','nine','ten'])
data2 = DataFrame(np.random.randint(0,20,(10,2)),columns=['a','b'])
data.plot(x='one',y='two',kind='scatter',ax=ax7) #针对DataFrame的一些作图
data2.plot(x='a',y='b',kind='bar',ax=ax8,color='red',legend=False)
data2.plot(x='a',y='b',kind='barh',color='m',ax=ax9)
#plt.tight_layout() #避免出现叠影
#plt.show()
2.蜡烛图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.finance as mpf
from pandas import Series, DataFrame
from matplotlib.pylab import date2num
%matplotlib inline
plt.rcParams['figure.autolayout'] = True
plt.rcParams['figure.figsize'] = 25,6
plt.rcParams['grid.alpha'] = .4
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams['font.sans-serif'] = ['SimHei']
fig, ax = plt.subplots(1,1,figsize=(12,5))
mpf.candlestick_ohlc(ax=ax,quotes=data2.values[::3],width=.002,colorup='red',colordown='green')
plt.xticks(data2.date[::25],data.date.map(lambda x:x[:5])[::25],rotation=0)
ax.twiny().plot(data3.Open)
plt.tight_layout();
3.热图
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
import matplotlib.pyplot as plt
%matplotlib inline
df = DataFrame(np.random.randn(10,10))
fig = plt.figure(figsize=(12,5))
ax = fig.add_subplot(111)
axim = ax.imshow(df.values,interpolation='nearest')#cmap=plt.cm.gray_r, #cmap用来显示颜色,可以另行设置
plt.colorbar(axim)
plt.show()
以上就是小编今天跟大家分享的matplotlib绘图的一些方法啦,希望对与大家使用matplotlib有所帮助。