数据的图表展示2 - 统计学实战

统计图形实战

#柱状图
ttnkh_dd = ttnkh.groupby('Pclass').count()['Name']
plt.figure(figsize=(6.4,4.8))
plt.bar(x=ttnkh_dd.index,height=ttnkh_dd.values,width=0.5,align='center')
​
plt.xlabel('等级',fontsize=10,labelpad=20)
plt.ylabel('人数',fontsize=10,labelpad=20)
plt.show()

temp2
#数据透视表
ttnkh_ts = ttnkh[['Sex','Fare','Pclass']]
temp1 = pd.pivot_table(data=ttnkh_ts,index='Pclass',columns='Sex',values='Fare',aggfunc=np.sum)
temp2 = pd.pivot_table(data=ttnkh_ts,index='Pclass',columns='Sex',values='Fare',aggfunc='count')
temp = temp1/temp2
temp
Sex	female	male
Pclass		
1	106.125798	67.226127
2	21.970121	19.741782
3	16.118810	12.661633
#堆叠柱状图 - 数据透视表
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor="white")
plt.bar(x=temp.index,height=temp['male'],color='green',label='男性',tick_label=['高级舱','中级舱','普通舱'])
plt.bar(x=temp.index,height=temp['female'],bottom = temp['male'],color='red',label='女性',tick_label=['高级舱','中级舱','普通舱'])
plt.legend(loc='best',fontsize=10,frameon=True,bbox_to_anchor=(1.2,0.8))
plt.xlabel('舱位等级',fontsize=10,labelpad=20)
plt.ylabel('人均票价',fontsize=10,labelpad=20)
plt.show()

#直方图 - 管擦和数据的分布形态,横坐标代表数值的分段,纵坐标代表观测数量和频数
#直方图有时候会和核密度图,正态分布图搭配使用,主要是为了更加详细的展示数据分布的特征
ttnkh_age = ttnkh.dropna(subset=['Age'])
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor='white')
plt.hist(x=ttnkh_age['Age'],bins=30,color='red',edgecolor='blue',density=True,)
plt.xlabel('年龄')
plt.ylabel('频率')
plt.title('年龄分布图',pad=20)
Text(0.5,1,'年龄分布图')

#正态分布函数
def normfun(x,mu,sigma):
    pdf = np.exp( - ((x - mu)**2)/(2*sigma*2))/(sigma*np.sqrt(2*np.pi))
    return pdf
​
#计算age的mean与str并将其带入正态分布函数
age_mean = ttnkh_age['Age'].mean()
age_str = ttnkh_age['Age'].std()
x = np.arange(ttnkh_age['Age'].min(),ttnkh_age['Age'].max()+10,1)
y = normfun(x,age_mean,age_str)#进行正态分布,核密度分布展示
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor='white')
plt.plot(x,y,color='g',linewidth=3,label='正态分布图')
ttnkh_age['Age'].plot(kind='kde',color='red',label='核密度图')
plt.hist(x=ttnkh_age['Age'],bins=30,color='red',edgecolor='blue',density=True,label='直方分布图')
plt.legend(loc='best',frameon=True,fontsize=10)
plt.xlabel('年龄')
plt.ylabel('频率')
plt.title('年龄分布图',pad=20)
Text(0.5,1,'年龄分布图')

填充箱体颜色,是否展示均值,是否展示异常值,箱体设置,异常值设置,均值设置,中位数设置
#箱线图 - 主要观察数据是否有异常(离群点)
#箱须-75%和25%的分位数+/-1.5倍分位差
plt.figure(figsize=(6.4,4.8),dpi=100)#是否填充箱体颜色,是否展示均值,是否展示异常值,箱体设置,异常值设置,均值设置,中位数设置
plt.boxplot(x=ttnkh_age['Age'],patch_artist=True,showmeans=True,showfliers=True,
           boxprops={'color':'black','facecolor':'white'},
           flierprops={'marker':'o','markersize':4,'markerfacecolor':'red'},
            meanprops={'marker':'o','markersize':6,'markerfacecolor':'indianred'},
           medianprops={'linestyle':'--','color':'blue'})
plt.show()

plt.scatter(x=ttnkh_age['Age'],y=ttnkh_age['Fare'],s=10,color='indianred')
plt.show()
#散点图 - 研究两个连续型变量之间的关系
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor='white')
plt.scatter(x=ttnkh_age['Age'],y=ttnkh_age['Fare'],s=10,color='indianred')
plt.show()

#不同船舱等级的分布散点图(分类散点图)
colors = ['steelblue','indianred','green']
labels = ['高级','中级','初级']
markers = ['o','s','x']
​
​
for i in range(0,3):
    plt.scatter(x=ttnkh_age.Age[ttnkh_age['Pclass'] == i],
                y=ttnkh_age.Fare[ttnkh_age['Pclass'] == i ],
                color=colors[i],marker=markers[i],label=labels[i])
plt.legend(loc='best',fontsize=10,frameon=True)
plt.xlabel('船舱等级',labelpad=10)
plt.ylabel('票价',labelpad=10)
plt.show()

#折线图 - 展示变化趋势,适合时间序列分析
os.chdir(r"D:/jupyter_notebook/eg/eg3-零售行业数据分析")
data = pd.read_csv("data.csv",encoding="ISO-8859-1")
data.head()
InvoiceNo	StockCode	Description	Quantity	InvoiceDate	UnitPrice	CustomerID	Country
0	536365	85123A	WHITE HANGING HEART T-LIGHT HOLDER	6	12/1/2010 8:26	2.55	17850.0	United Kingdom
1	536365	71053	WHITE METAL LANTERN	6	12/1/2010 8:26	3.39	17850.0	United Kingdom
2	536365	84406B	CREAM CUPID HEARTS COAT HANGER	8	12/1/2010 8:26	2.75	17850.0	United Kingdom
3	536365	84029G	KNITTED UNION FLAG HOT WATER BOTTLE	6	12/1/2010 8:26	3.39	17850.0	United Kingdom
4	536365	84029E	RED WOOLLY HOTTIE WHITE HEART.	6	12/1/2010 8:26	3.39	17850.0	United Kingdom
#生成数据副本
data_ls = data.dropna(how='any').copy()
data_ls.head()
InvoiceNo	StockCode	Description	Quantity	InvoiceDate	UnitPrice	CustomerID	Country
0	536365	85123A	WHITE HANGING HEART T-LIGHT HOLDER	6	12/1/2010 8:26	2.55	17850.0	United Kingdom
1	536365	71053	WHITE METAL LANTERN	6	12/1/2010 8:26	3.39	17850.0	United Kingdom
2	536365	84406B	CREAM CUPID HEARTS COAT HANGER	8	12/1/2010 8:26	2.75	17850.0	United Kingdom
3	536365	84029G	KNITTED UNION FLAG HOT WATER BOTTLE	6	12/1/2010 8:26	3.39	17850.0	United Kingdom
4	536365	84029E	RED WOOLLY HOTTIE WHITE HEART.	6	12/1/2010 8:26	3.39	17850.0	United Kingdom
#转换时间日期格式,单独一行转换
data_ls['InvoiceDate'] = pd.to_datetime(data_ls['InvoiceDate'],errors='coerce')
data_ls
#提取年月日,并将其作为列索引
data_ls['InvoiceDate'] = data_ls['InvoiceDate'].dt.date
data_ls.set_index(['InvoiceDate'],inplace=True)
data_ls.info()
<class 'pandas.core.frame.DataFrame'>
Index: 406829 entries, 2010-12-01 to 2011-12-09
Data columns (total 7 columns):
InvoiceNo      406829 non-null object
StockCode      406829 non-null object
Description    406829 non-null object
Quantity       406829 non-null int64
UnitPrice      406829 non-null float64
CustomerID     406829 non-null float64
Country        406829 non-null object
dtypes: float64(2), int64(1), object(4)
memory usage: 24.8+ MB
#将行索引转换为时间数据格式
data_ls.index = pd.to_datetime(data_ls.index)
M
#计算月总和 (时间数据.resample)
data_month_sum = data_ls.resample('M').sum()
print(data_month_sum)
             Quantity   UnitPrice    CustomerID
InvoiceDate                                    
2010-12-31     296362   86057.190  4.166977e+08
2011-01-31     269379   73202.320  3.319198e+08
2011-02-28     262833   67529.430  3.117809e+08
2011-03-31     344012   96183.240  4.223298e+08
2011-04-30     278585   91117.721  3.541194e+08
2011-05-31     367852  125537.660  4.400088e+08
2011-06-30     356922  129301.450  4.264710e+08
2011-07-31     363418   92754.521  4.209226e+08
2011-08-31     386612   88126.750  4.219478e+08
2011-09-30     537496  126029.422  6.229373e+08
2011-10-31     569666  186583.000  7.727017e+08
2011-11-30     669915  195298.520  1.007384e+09
2011-12-31     203836   50098.740  2.702551e+08
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor='white')
#画出散点图
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor='white')
plt.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',
        data_month_sum.index,data_month_sum.iloc[:,1],'rs--')
plt.xlabel('年份',labelpad=20,fontsize=10)
​
plt.legend(['Quantity','UnitPrice'],loc='best',frameon=True,bbox_to_anchor=[1.1,0.9],ncol=1,title='月销量与月成交价')
plt.title('月销量与月成交价',size=24,color='darkblue',pad=20)
plt.show()

#设置横轴时间显示格式
ax = plt.gca()
date_format = mpl.dates.DateFormatter('%Y-%m-%d')     #设置时间显示格式
ax.xaxis.set_major_formatter(date_format) 
xlocator=mpl.ticker.LinearLocator(12)                 #设置时间轴标签个数,会自动生成
ax.xaxis.set_major_locator(xlocator)

#画出折线图
plt.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',
        data_month_sum.index,data_month_sum.iloc[:,1],'rs--')
plt.xlabel('年份',labelpad=20,fontsize=10)
plt.xticks(rotation=45)          #将坐标轴标签旋转45度
plt.legend(['Quantity','UnitPrice'],loc='best',frameon=True,bbox_to_anchor=[1.1,0.9],ncol=1,title='月销量与月成交价')
plt.title('月销量与月成交价',size=24,color='darkblue',pad=20)
plt.show()
#改变时间序列的横轴显示格式import matplotlib as mpl
#设置画布
plt.figure(figsize=(6.4,4.8),dpi=100,facecolor='white')#设置横轴时间显示格式
ax = plt.gca()
date_format = mpl.dates.DateFormatter('%Y-%m-%d')     #设置时间显示格式
ax.xaxis.set_major_formatter(date_format) 
xlocator=mpl.ticker.LinearLocator(12)                 #设置时间轴标签个数,会自动生成
ax.xaxis.set_major_locator(xlocator)#画出折线图
plt.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',
        data_month_sum.index,data_month_sum.iloc[:,1],'rs--')
plt.xlabel('年份',labelpad=20,fontsize=10)
plt.xticks(rotation=45)          #将坐标轴标签旋转45度
plt.legend(['Quantity','UnitPrice'],loc='best',frameon=True,bbox_to_anchor=[1.1,0.9],ncol=1,title='月销量与月成交价')
plt.title('月销量与月成交价',size=24,color='darkblue',pad=20)
plt.show()

图形样式高级操作

ax1 = fig.add_subplot(1,1,1)
ax1.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',label='月销量')
ax1.set_ylabel('月销量')
plt.legend(loc='best')
ax2 = ax1.twinx()
ax2.plot(data_month_sum.index,data_month_sum.iloc[:,2],'gs--',label='订单编号+')
ax2.set_ylabel("订单编号+'")
plt.legend(loc='upper center')
plt.show()
#绘制双坐标轴 - 变量之间量纲级不一样,如果绘制在同一坐标轴上,量纲级较小的变量很难看出变化趋势,
#所以需要绘制双坐标轴,来显示两个变量的趋势
fig = plt.figure(figsize=(6.4,4.8))
ax1 = fig.add_subplot(1,1,1)
ax1.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',label='月销量')
ax1.set_ylabel('月销量')
plt.legend(loc='best')
ax2 = ax1.twinx()
ax2.plot(data_month_sum.index,data_month_sum.iloc[:,2],'gs--',label='订单编号+')
ax2.set_ylabel("订单编号+'")
plt.legend(loc='upper center')
plt.show()

,
#多个图形的合并
#绘制双坐标轴 - 变量之间量纲级不一样,如果绘制在同一坐标轴上,量纲级较小的变量很难看出变化趋势,
#所以需要绘制双坐标轴,来显示两个变量的趋势
plt.figure(figsize=(24,12))#绘制第一个图
plt.subplot(1,2,1)
#设置横轴时间显示格式
ax = plt.gca()
date_format = mpl.dates.DateFormatter('%Y-%m-%d')     #设置时间显示格式
ax.xaxis.set_major_formatter(date_format) 
xlocator=mpl.ticker.LinearLocator(12)                 #设置时间轴标签个数,会自动生成
ax.xaxis.set_major_locator(xlocator)
#画出折线图
plt.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',
        data_month_sum.index,data_month_sum.iloc[:,1],'rs--')
plt.xlabel('年份',labelpad=20,fontsize=10)
plt.xticks(rotation=45)          #将坐标轴标签旋转45度
plt.legend(['Quantity','UnitPrice'],loc='best',frameon=True,ncol=1,title='月销量与月成交价')
plt.title('月销量与月成交价',size=24,color='darkblue',pad=20)#绘制第二幅图
ax1 = plt.subplot(1,2,2)
ax1.plot(data_month_sum.index,data_month_sum.iloc[:,0],'bs--',label='月销量')
ax1.set_ylabel('月销量')
plt.legend(loc='best')
ax2 = ax1.twinx()
ax2.plot(data_month_sum.index,data_month_sum.iloc[:,2],'gs--',label='订单编号+')
ax2.set_ylabel("订单编号+'")
plt.legend(loc='upper center')
plt.show()
​
​
#注意plt.show()必须在最后一个,否则会出现显示问题

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了5 篇原创文章 · 获赞 0 · 访问量 34

猜你喜欢

转载自blog.csdn.net/qq_27924553/article/details/105142184