本文实例讲述了Python使用matplotlib和pandas实现的画图操作。分享给大家供大家参考,具体如下:
画图在工作再所难免,尤其在做数据探索时候,下面总结了一些关于python画图的例子
#encoding:utf-8'''''Created on 2015年9月11日@author: ZHOUMEIXU204'''# pylab 是 matplotlib 面向对象绘图库的一个接口。它的语法和 Matlab 十分相近import pandas as pd#from ggplot import *import numpy as npimport matplotlib.pyplot as pltdf=pd.DataFrame(np.random.randn(1000,4),columns=list('ABCD'))df=df.cumsum()print(plt.figure())print(df.plot())print(plt.show())# print(ggplot(df,aes(x='A',y='B'))+geom_point())
运行效果:
# 画简单的图形from pylab import *x=np.linspace(-np.pi,np.pi,256,endpoint=True)c,s=np.cos(x),np.sin(x)plot(x,c, color="blue", linewidth=2.5, linestyle="-", label="cosine") #label用于标签显示问题plot(x,s,color="red", linewidth=2.5, linestyle="-", label="sine")show()
运行效果:
#散点图from pylab import *n = 1024X = np.random.normal(0,1,n)Y = np.random.normal(0,1,n)scatter(X,Y)show()
运行效果:
#条形图from pylab import *n = 12X = np.arange(n)Y1 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)Y2 = (1-X/float(n)) * np.random.uniform(0.5,1.0,n)bar(X, +Y1, facecolor='#9999ff', edgecolor='white')bar(X, -Y2, facecolor='#ff9999', edgecolor='white')for x,y in zip(X,Y1): text(x+0.4, y+0.05, '%.2f' % y, ha='center', va= 'bottom')ylim(-1.25,+1.25)show()
运行效果:
#饼图from pylab import *n = 20Z = np.random.uniform(0,1,n)pie(Z), show()
运行效果:
#画三维图import numpy as npfrom mpl_toolkits.mplot3d import Axes3Dfrom pylab import *fig=figure()ax=Axes3D(fig)x=np.arange(-4,4,0.1)y=np.arange(-4,4,0.1)x,y=np.meshgrid(x,y)R=np.sqrt(x**2+y**2)z=np.sin(R)ax.plot_surface(x,y,z,rstride=1,cstride=1,cmap='hot')show()
运行效果:
#用于图像显示的问题import matplotlib.pyplot as pltimport pandas as pdweights_dataframe=pd.DataFrame()plt.figure()plt.plot(weights_dataframe.weights_ij,weights_dataframe.weights_x1,label='weights_x1')plt.plot(weights_dataframe.weights_ij,weights_dataframe.weights_x0,label='weights_x0')plt.plot(weights_dataframe.weights_ij,weights_dataframe.weights_x2,label='weights_x2')plt.legend(loc='upper right') #用于标签显示问题plt.xlabel(u"迭代次数", fontproperties='SimHei')plt.ylabel(u"参数变化", fontproperties='SimHei')plt.title(u"迭代次数显示", fontproperties='SimHei') #fontproperties='SimHei' 用于可以显示中文plt.show()import matplotlib.pyplot as pltfrom numpy.random import randomcolors = ['b', 'c', 'y', 'm', 'r']lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])l = plt.scatter(random(10), random(10), marker='o', color=colors[1])a = plt.scatter(random(10), random(10), marker='o', color=colors[2])h = plt.scatter(random(10), random(10), marker='o', color=colors[3])hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])plt.legend((lo, ll, l, a, h, hh, ho), ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'), scatterpoints=1, loc='lower left', ncol=3, fontsize=8)plt.show()
新闻热点
疑难解答