读取数据与数据处理阶段
提取指定行中的数据
data=data[['year','quarter','pop','realgdp']]
得到>指定数值的数据
data=data.loc[(data['year']>=1990),:]
得到=指定值得数据
data=data.loc[data['quarter']==4,:]
整体的数据处理:
data=pd.read_csv('./macrodata.csv')
data0=data
data=data[['year','quarter','pop','realgdp']]
data_scatter=data
data=data.loc[(data['year']>=1990),:]
data=data.loc[data['quarter']==4,:]
画图函数
plt.subplots()
参数列表:
fig,ax=plt.subplots(1,2, figsize=(8, 4.8))
返回值 fig: matplotlib.figure.Figure 对象 ax:子图对象( matplotlib.axes.Axes)或者是他的数组 在matplotlib中,整个图像为一个Figure对象。在Figure对象中可以包含一个或者多个Axes对象。每个Axes(ax)对象都是一个拥有自己坐标系统的绘图区域
plt.subplots_adjust()
plt.subplots_adjust(left=0.15,bottom=0.14,right=0.95,top=0.65,hspace=0.12,wspace =0.25)
参数含义: left, right, bottom, top:子图所在区域的边界。
设置x轴y轴的刻度和标签
ax[0].set_xlim(1989, 2009)
ax[0].set_ylim(7000,14000)
ax[0].set_xticks(yearxticks)
plt.xlim(240,320)
plt.ylim(7000,14000)
plt.xticks(np.arange(240,321,20),fontsize=14)
plt.yticks(fontsize=14)
使用中文标题在作图时
plt.rcParams[‘font.sans-serif’] = [‘SimHei’] # 用来正常显示中文标签
画折线图(plot)
print('画折线图')
from matplotlib import pyplot as plt
fig,ax=plt.subplots(1,2, figsize=(8, 4.8))
yearxticks=[i for i in range(1990,2010,2)]
plt.subplots_adjust(left=0.15,bottom=0.14,right=0.95,top=0.65,hspace=0.12,wspace =0.25)
ax[0].set_xlim(1989, 2009)
ax[0].set_ylim(7000,14000)
ax[0].set_xticks(yearxticks)
ax[0].plot(data['year'],data['realgdp'],'o-')
ax[0].set_xticklabels(yearxticks,rotation=30)
ax[0].set_ylabel('GDP (${10^{4}}$ USD)')
ax[0].set_title('(a) GDP (1990-2009)')
ax[1].set_ylim(240,320)
ax[1].set_xticks(yearxticks)
ax[1].plot(data['year'],data['pop'],'o-')
ax[1].set_xticklabels(yearxticks,rotation=30)
ax[1].set_ylabel('Population (${10^4}$)')
ax[1].set_title('(b) Population (1990-2009)')
plt.show()
画散点图(scatter)
print('画散点图')
plt.figure(figsize=(8, 7.2))
plt.scatter(data_scatter['pop'],data_scatter['realgdp'],marker='o',color='blue',edgecolors='k', s=100)
plt.xlim(240,320)
plt.ylim(7000,14000)
plt.xticks(np.arange(240,321,20),fontsize=14)
plt.yticks(fontsize=14)
plt.title('Population versus GDP',fontsize=18)
plt.xlabel('Population (${10^4}$)',fontsize=14)
plt.ylabel('GDP (${10^{4}}$ USD)',fontsize=14)
plt.show()
画拟合曲线
拟合线方程中的参数可以使用numpy.polyfit(x, y, degree)函数来确定 图例使用 plt.legend(loc = 4,fontsize = fontsize2) 其中4表示放置位置,fontsize表示字体大小。 文本使用plt.text(xPosition, yPostion, text, fontdict ={…})来添加,其中xPosition, yPostion表示文本左上角在坐标系中的实际坐标,并非比例因子;text表示需要添加的文本或字符串;fontdict表示一个参数字典,用于确定文本字体的大小、是否加粗、字体等
拟合指数R方
t=np.polyfit(x,y,1)
f=np.poly1d(t)
xvals=np.arange(np.min(x),np.max(x))
yvals=f(xvals)
r2=np.around(r2_score(y,f(x)),decimals=2)
t=np.around(t, decimals=2)
print('画拟合曲线')
from sklearn.metrics import r2_score
x=data['pop']
y=data['realgdp']
t=np.polyfit(x,y,1)
f=np.poly1d(t)
xvals=np.arange(np.min(x),np.max(x))
yvals=f(xvals)
r2=np.around(r2_score(y,f(x)),decimals=2)
t=np.around(t, decimals=2)
plt.figure(figsize=(8, 7.2))
p1=plt.scatter(x,y,marker='o',color='blue',edgecolors='k', s=200)
p2=plt.plot(xvals,yvals,'k')
plt.xlim(240,320)
plt.ylim(7000,14000)
plt.xticks(np.arange(240,321,20),fontsize=14)
plt.yticks(fontsize=14)
plt.title('Population versus GDP',fontsize=18)
plt.xlabel('Population (${10^4}$)',fontsize=14)
plt.ylabel('GDP (${10^{4}}$ USD)',fontsize=14)
plt.legend(['Fitted line','Sample'],loc=4,fontsize='xx-large')
text='y='+str(t[0])+'x'+str(t[1])
plt.text(250,13500, text,fontsize=12)
text='${R^2}$='+str(r2)
plt.text(250,13000,text,fontsize=12)
plt.show()
画箱线图
print('画箱线图')
fig,ax=plt.subplots(1,2, figsize=(10, 4.8))
infl_by_quarter=[data0.loc[data0['quarter']==i,:]['infl'] for i in range(1,5)]
realint_by_quarter=[data0.loc[data0['quarter']==i,:]['realint'] for i in range(1,5)]
titles=['Rectangular box plot','Notched box plot']
bplot0=ax[0].boxplot(infl_by_quarter,patch_artist=True)
bplot1=ax[1].boxplot(realint_by_quarter,patch_artist=True,notch=True)
for i in range(0,2):
ax[i].grid(axis='y')
ax[i].set_title(titles[i])
ax[i].set_ylabel('Observed values')
ax[i].set_xlabel('Season')
colors = ['pink', 'lightblue', 'lightgreen', 'lightcyan']
for bplot in (bplot0,bplot1):
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
plt.show()
画直方图(hist)与柱状图(bar)
print('画直方图与柱状图')
infl_quarter_mean=data0.groupby(by='quarter').agg({'infl':np.mean})
fig,ax=plt.subplots(1,2,figsize=(12,4.8))
ax[0].hist(data0['infl'],bins=20,density=True,color='g')
ax[0].set_title('Histogram of infl')
ax[0].set_xlabel('infl')
ax[0].set_ylabel('Probability')
ax[0].set_xticks([-5,0,5,10])
ax[1].bar(np.arange(1,5),infl_quarter_mean['infl'],width=0.5,color='g')
ax[1].legend(['infl'],loc=1)
ax[1].set_title('Bar of Seasonal infl')
ax[1].set_xlabel('infl')
ax[1].set_ylabel('Probability')
ax[1].set_xticks([1,2,3,4])
ax[1].set_xticklabels(['1','2','3','4'],rotation=90)
plt.show()
input('按回车键结束')
代码实现
#!/usr/bin/env python
import numpy as np
import pandas as pd
data=pd.read_csv('./macrodata.csv')
data0=data
data=data[['year','quarter','pop','realgdp']]
data_scatter=data
data=data.loc[(data['year']>=1990),:]
data=data.loc[data['quarter']==4,:]
print('读入数据')
print('画折线图')
from matplotlib import pyplot as plt
fig,ax=plt.subplots(1,2, figsize=(8, 4.8))
yearxticks=[i for i in range(1990,2010,2)]
plt.subplots_adjust(left=0.15,bottom=0.14,right=0.95,top=0.65,hspace=0.12,wspace =0.25)
ax[0].set_xlim(1989, 2009)
ax[0].set_ylim(7000,14000)
ax[0].set_xticks(yearxticks)
ax[0].plot(data['year'],data['realgdp'],'o-')
ax[0].set_xticklabels(yearxticks,rotation=30)
ax[0].set_ylabel('GDP (${10^{4}}$ USD)')
ax[0].set_title('(a) GDP (1990-2009)')
ax[1].set_ylim(240,320)
ax[1].set_xticks(yearxticks)
ax[1].plot(data['year'],data['pop'],'o-')
ax[1].set_xticklabels(yearxticks,rotation=30)
ax[1].set_ylabel('Population (${10^4}$)')
ax[1].set_title('(b) Population (1990-2009)')
plt.show()
print('画散点图')
plt.figure(figsize=(8, 7.2))
plt.scatter(data_scatter['pop'],data_scatter['realgdp'],marker='o',color='blue',edgecolors='k', s=100)
plt.xlim(240,320)
plt.ylim(7000,14000)
plt.xticks(np.arange(240,321,20),fontsize=14)
plt.yticks(fontsize=14)
plt.title('Population versus GDP',fontsize=18)
plt.xlabel('Population (${10^4}$)',fontsize=14)
plt.ylabel('GDP (${10^{4}}$ USD)',fontsize=14)
plt.show()
print('画拟合曲线')
from sklearn.metrics import r2_score
x=data['pop']
y=data['realgdp']
t=np.polyfit(x,y,1)
f=np.poly1d(t)
xvals=np.arange(np.min(x),np.max(x))
yvals=f(xvals)
r2=np.around(r2_score(y,f(x)),decimals=2)
t=np.around(t, decimals=2)
plt.figure(figsize=(8, 7.2))
p1=plt.scatter(x,y,marker='o',color='blue',edgecolors='k', s=200)
p2=plt.plot(xvals,yvals,'k')
plt.xlim(240,320)
plt.ylim(7000,14000)
plt.xticks(np.arange(240,321,20),fontsize=14)
plt.yticks(fontsize=14)
plt.title('Population versus GDP',fontsize=18)
plt.xlabel('Population (${10^4}$)',fontsize=14)
plt.ylabel('GDP (${10^{4}}$ USD)',fontsize=14)
plt.legend(['Fitted line','Sample'],loc=4,fontsize='xx-large')
text='y='+str(t[0])+'x'+str(t[1])
plt.text(250,13500, text,fontsize=12)
text='${R^2}$='+str(r2)
plt.text(250,13000,text,fontsize=12)
plt.show()
print('画箱线图')
fig,ax=plt.subplots(1,2, figsize=(10, 4.8))
infl_by_quarter=[data0.loc[data0['quarter']==i,:]['infl'] for i in range(1,5)]
realint_by_quarter=[data0.loc[data0['quarter']==i,:]['realint'] for i in range(1,5)]
titles=['Rectangular box plot','Notched box plot']
bplot0=ax[0].boxplot(infl_by_quarter,patch_artist=True)
bplot1=ax[1].boxplot(realint_by_quarter,patch_artist=True,notch=True)
for i in range(0,2):
ax[i].grid(axis='y')
ax[i].set_title(titles[i])
ax[i].set_ylabel('Observed values')
ax[i].set_xlabel('Season')
colors = ['pink', 'lightblue', 'lightgreen', 'lightcyan']
for bplot in (bplot0,bplot1):
for patch, color in zip(bplot['boxes'], colors):
patch.set_facecolor(color)
plt.show()
print('画直方图与柱状图')
infl_quarter_mean=data0.groupby(by='quarter').agg({'infl':np.mean})
fig,ax=plt.subplots(1,2,figsize=(12,4.8))
ax[0].hist(data0['infl'],bins=20,density=True,color='g')
ax[0].set_title('Histogram of infl')
ax[0].set_xlabel('infl')
ax[0].set_ylabel('Probability')
ax[0].set_xticks([-5,0,5,10])
ax[1].bar(np.arange(1,5),infl_quarter_mean['infl'],width=0.5,color='g')
ax[1].legend(['infl'],loc=1)
ax[1].set_title('Bar of Seasonal infl')
ax[1].set_xlabel('infl')
ax[1].set_ylabel('Probability')
ax[1].set_xticks([1,2,3,4])
ax[1].set_xticklabels(['1','2','3','4'],rotation=90)
plt.show()
input('按回车键结束')
|