python中用作数据可视化的工具有多种,其中matplotlib最为基础。故在工具选择上,图形美观之外,操作方便即上乘。
本文着重说明常见图表用基础版matplotlib和改良版pyecharts作图间的差异
一、maplotlib
基本用法如下:
import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt import matplotlib.finance as mpf %matplotlib inline fig = plt.figure(figsize=(10,8)) #建立一个大小为10*8的画板 ax1 = fig.add_subplot(321) #在画板上添加3*3个画布,位置是第1个 ax2 = fig.add_subplot(3,2,2) ax3 = fig.add_subplot(3,2,3) ax4 = fig.add_subplot(3,2,4) ax5 = fig.add_subplot(3,2,5) ax6 = fig.add_subplot(3,2,6) data1 = np.random.randn(20) x = np.arange(20) ax1.plot(data1) #作折线图 ax2.scatter(data1,data1,color='r') #作散点图 ax3.hist(data1,bins=10,alpha=0.3) #作直方图 ax4.bar(x,data1) #作柱形图 ax5.pie(np.random.randint(1,15,5),explode=[0,0,0.2,0,0]) #作饼形图 ax6.plot(x,data1,color='green') #组合图 ax6.bar(x,data1,color='k') fig,axes = plt.subplots(3,3,figsize=(20,16))
data2 = DataFrame(np.random.randn(10,5),columns = ['A','B','C','D','E'],index = np.arange(0,100,10))
data2.plot(kind='line',ax=axes[0][0]) #作折线图
data2.plot(kind = 'scatter',x = data2.index[0] ,y = data2.index[0],ax=axes[0][1]) #作散点图
data2.plot(kind='hist',ax=axes[0][2],legend=False) #作直方图
data2.plot(kind='bar',ax=axes[1][0]) #作柱形图
data2.plot(kind='area',ax=axes[1][1],stacked = False) #面积图
train_data = np.array(data2)
mpf.candlestick_ohlc(axes[1][2],train_data.tolist(),width=1.5,colorup='r',colordown='g') #K线图
axim = axes[2][0].imshow(data2.values,interpolation='nearest