Matplotlib.pyplot学习

from __future__ import division
from numpy.random import randn
import numpy as np
import os
import matplotlib.pyplot as plt
np.random.seed(12345)
plt.rc('figure',figsize=(10,6))
from pandas import Series,DataFrame
import pandas as pd
np.set_printoptions(precision=4)#输出小数点后4位数字

get_ipython().magic(u'matplotlib inline') #把图像画在jupyter notebook里面
get_ipython().magic(u'pwd')

简单图形

x=[1,2,3,4]
y=[5,4,3,2]

fig,axes=plt.subplots(2,3)
axes[0,0].plot(x,y)
axes[0,1].bar(x,y)
axes[0,2].barh(x,y)
axes[1,0].boxplot(x,y)
axes[1,1].scatter(x,y)
plt.show()
plt.savefig('E:/python/wangyiPython/the seventh week/1.png',dpi=400,bbox_inches='tight')

#figure对象
fig=plt.figure()
ax1=fig.add_subplot(221)
ax2=fig.add_subplot(222)
ax=fig.add_subplot(223)
plt.show()
plt.savefig('E:/python/wangyiPython/the seventh week/2.png',dpi=400,bbox_inches='tight')

 

#调整subplot周围的间距
fig,axes=plt.subplots(2,3)
plt.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
axes
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)
plt.savefig('E:/python/wangyiPython/the seventh week/5.png',dpi=400,bbox_inches='tight')

#matplotlib基本设置  颜色、标记和线型

plt.figure()
plt.plot(x,y,linestyle='--',color='g')

plt.plot(randn(30).cumsum(),'bo--')

plt.plot(randn(30).cumsum(),linestyle='dashed',color='b',marker='o')

plt.close('all')
data=randn(30).cumsum()
plt.plot(data,'g--',label='Default')
plt.plot(data,'r--',drawstyle='steps-post',label='steps_post')
plt.legend('best')
plt.savefig('E:/python/wangyiPython/the seventh week/6.png',dpi=400,bbox_inches='tight')

 

#设置标题、轴标签、刻度以及刻度标签
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(randn(1000).cumsum())
ticks=ax.set_xticks([0,250,500,750,1000])
labels=ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],rotation=30, fontsize='small')
ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')

 

#添加图例
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(randn(1000).cumsum(),'r',label='one')
ax.plot(randn(1000).cumsum(),'b--',label='two')
ax.plot(randn(1000).cumsum(),'g.',label='three')
ax.legend('best')

#添加注释
fig=plt.figure()
ax=fig.add_subplot(111)
spx = data['SPX']
spx.plot(ax=ax, style='b-')
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='red'),#设置箭头颜色
                horizontalalignment='left', verticalalignment='top')#文字相对于箭头的位置

ax.set_xlim(['1/1/2007','1/1/2011'])
ax.set_ylim([600,1800])
ax.set_title('Important dates in 2008-2009 financial crisis')
plt.show()
plt.savefig('E:/python/wangyiPython/the seventh week/7.png',dpi=400,bbox_inches='tight')

#长方形 圆形 三角形
fig=plt.figure()
ax=fig.add_subplot(111)
rect=plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.4)
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.4)
ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
fig.savefig('E:/python/wangyiPython/the seventh week/rcp.svg')
fig.savefig('E:/python/wangyiPython/the seventh week/rcp.png')

 

#matplotlib配置

plt.rc('figure',figsize=(10,10))
font_options={'family':'monospace',
             'weight':'bold',
             'size':16}
plt.rc('font',**font_options)

#pandas中的绘图函数 线图
s=Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s.plot(style='bo-')
df=DataFrame(np.random.randn(10,4).cumsum(0),columns=['A','B','C','D'],index=np.arange(0,100,10))
df.plot()


#柱形图
fig,axes=plt.subplots(2,2)
data=Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar',ax=axes[0,0],color='k',alpha=0.7)
data.plot(kind='barh',ax=axes[0,1],color='k',alpha=0.7)
df=DataFrame(np.random.rand(6,4),index=['one', 'two', 'three', 'four', 'five', 'six'],
             columns=pd.Index(['A', 'B', 'C', 'D'],name='Genus'))
df.plot(kind='bar',ax=axes[1,0])
df.plot(kind='barh',stacked=True,ax=axes[1,1])
plt.legend('best')
plt.savefig('E:/python/wangyiPython/the seventh week/8.png',dpi=400,bbox_inches='tight')

plt.figure()
tips=pd.read_csv('E:/python/wangyiPython/the seventh week/my resource/tips.csv')
party_counts=pd.crosstab(tips.day,tips['size'])#交叉表crosstab ,按照指定的行和列统计分组频数
party_counts=party_counts.ix[:,2:5]
party_pcts=party_counts.div(party_counts.sum(1).astype(float),axis=0)#进行归一化是各行和为1
party_pcts.plot(kind='bar', stacked=True,alpha=0.5)

#直方图和密度图

plt.figure()
tips['tip_pct']=tips['tip']/tips['total_bill']
tips['tip_pct'].hist(bins=50,facecolor='b',edgecolor='k',alpha=0.8)
plt.show()

plt.figure()
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='k--')
plt.savefig('E:/python/wangyiPython/the seventh week/9.png',dpi=400,bbox_inches='tight')

#散点图
macro=pd.read_csv('E:/python/wangyiPython/the seventh week/my resource/macrodata.csv')
data=macro[['cpi', 'm1', 'tbilrate', 'unemp']]
trans_data=np.log(data).diff().dropna()
plt.figure()
plt.scatter(trans_data['m1'],trans_data['unemp'])
plt.title('Changes in log %s vs.log %s' % ('m1','unemp'))

pd.plotting.scatter_matrix(trans_data,color='k',diagonal='kde',alpha=0.3)

#Matplotlib作图误差条形图

'''
left:x轴的位置序列
height:y轴的数值序列,即柱形图的高度
xerr/yerr:用于在柱状图上生成误差条
linewidth:误差条边界宽度,可以设为None(默认值)和0(此时误差条边界将不显示出来)
ecolor:指定误差条的颜色
edgecolor:指定误差条边界颜色
width:指定误差条的宽度,默认值为0.8
bottom:如果指定了bottom,其值会加到高度中,默认值为None'''

x=np.arange(0,10,1)
y=np.log(x)
xe=0.1 * np.abs(np.random.randn(len(y)))
plt.bar(x,y,yerr=xe,width=0.4,align='center',ecolor='r',color='b',alpha=0.7,label='experiment #1')
plt.xlabel('# measurement')
plt.ylabel('Measured values')
plt.title('Measurements')
plt.legend(loc='upper left')
plt.show()

饼图
plt.figure(1,figsize=(8,8))
ax=plt.axes([0.1,0.1,0.8,0.8])
labels=['Spring', 'Summer', 'Autumn', 'Winter']
values=[15, 16, 16, 28]
explode=[0,0,0,0.1]
plt.pie(values,explode=explode,labels=labels,autopct='%1.1f%%',startangle=67)
plt.title('Rainy days by season')
plt.show()

#等高线图
import matplotlib as mpl

def process_signals(x,y):
    return(1-(x**2+y**2))*np.exp(-y**3/3)
x=np.arange(-1.5,1.5,0.1)
y=np.arange(-1.5,1.5,0.1)#30个数据
X,Y=np.meshgrid(x,y)#将原始数据变成网格数据形式
Z=process_signals(X,Y)
N=np.arange(-1,1.5,0.3)
CS=plt.contour(Z,N,linewidths=2,cmap=mpl.cm.jet) # 绘制等高线
plt.clabel(CS,inline=True,fmt='%1.1f',fonsize=10)#绘制等高线数据
plt.colorbar(CS)
plt.title('My function: $z=(1-x^2+y^2) e^{-(y^3)/3}$')
plt.show()

#3D图像
#3d柱形图

import matplotlib.dates as mdates
from mpl_toolkits.mplot3d import Axes3D

mpl.rcParams['font.size']=10
fig=plt.figure()
ax=fig.add_subplot(111,projection='3d')
for z in [2011,2012,2013,2014]:
    xs=range(1,13)
    ys=1000*np.random.rand(12)
    color=plt.cm.Set2(np.random.choice(range(plt.cm.Set2.N)))
    ax.bar(xs,ys,zs=z,zdir='y',color=color,alpha=0.8)
'''
1.xs和ys:x轴和y轴坐标。

2.zs:这是z轴的坐标值,可以是所有点对应一个值,或者是每个点对应一个值。

3.zdir:决定哪个坐标轴作为z轴的维度(通常是zs,但是也可以是xs或者ys)
'''

ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))
ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))

ax.set_xlabel('Month')
ax.set_ylabel('Year')
ax.set_zlabel('Sales Net [usd]')

plt.show()

 

#直方图

mpl.rcParams['font.size'] = 10

samples = 25

x = np.random.normal(5, 1, samples)
y = np.random.normal(3, .5, samples)

fig = plt.figure()
ax = fig.add_subplot(211, projection='3d')

hist, xedges, yedges = np.histogram2d(x, y, bins=10)

elements = (len(xedges) - 1) * (len(yedges) - 1)
xpos, ypos = np.meshgrid(xedges[:-1]+.25, yedges[:-1]+.25)

xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(elements)

dx = .1 * np.ones_like(zpos)
dy = dx.copy()

dz = hist.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', alpha=0.4)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')

ax2 = fig.add_subplot(212)
ax2.scatter(x, y)
ax2.set_xlabel('X Axis')
ax2.set_ylabel('Y Axis')

plt.show()

 

猜你喜欢

转载自blog.csdn.net/qq_42052864/article/details/81704304