暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

技能篇—python(二)用Python让Excel飞起来6

Gavin的数据分析进阶之路 2021-11-23
627

上一篇方差分析补充代码:

import pandas as pd
from statsmodels.formula.api import ols #导入统计方程模块中的ols()函数
from statsmodels.stats.anova import anova_lm #导入统计方差分析模块中的anova_lm()函数
df=pd.read_excel('c:\\users\\vitto\\desktop\\test2.xlsx',sheet_name=1)
df_melt=df.melt()#列名转化为列数据,重构DataFrame
df_melt.columns=['type','value']
model=ols('value~C(type)',data=df_melt).fit()#最小二乘线性拟合计算
anova_lm(model,typ=3)#方差分析

(6)绘图:

①简单图表:plt.plot(x,y,color,linewidth粗细,linestyle) #常用b\g\r\c\m\y\k\w八种颜色,常用style有-/--/-./:/空。举例:x=[1,2,3,4,5,6],y1=[2,4,6,9,10,12],y2=[1.7,2.6,3.8,9.4,6.2,5.9],plt.plot(x,y1,'r*-',x,y2,'b--') #柱形图plt.bar(x,y1,width=0.8,bottom=None,align='center',color='r',edgecolor='k',linewidth=2) #plt.barh,条形图,部分参数如width不能用;plt.pie(x) #饼图;plt.scatter(x,y1,color='r',marker='*',s=200) #s表示面积(如果有多个参数就变成了气泡图),'*'这里表示五角星,绘制散点图; plt.stackplot(x,y1,y2,colors=['r','b']) #面积图
②组合图表:在简单图表基础上,如plt.plot折线图后只添加plt.bar条形图一行代码。具体代码如下:

figure=plt.figure() #创建绘图窗口
plt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码问题
plt.rcParams['axes.unicode_minus']=False #解决符号显示问题
x=[1,2,3,4,5,6]
y1=[2,-4,6,9,10,12]
y2=[1.7,-2.6,3.8,9.4,6.2,5.9]
plt.title(label='各利润额的对比图',fontdict={'family':'SimHei','color':'blue','size':30},loc='center')
plt.xlabel('月份',fontdict={'family':'SimSun','color':'c','size':15},loc='center')
plt.bar(x,y1,width=0.8,align='center',color='r',edgecolor='k',linewidth=0.5,label='利润') #此处设置图例名才能在plt.legend中显示
plt.legend(loc='upper left',fontsize=15,facecolor='c',edgecolor='r',shadow=True)
plt.ylabel('利润',fontdict={'family':'SimSun','color':'r','size':15},loc='top')
plt.twinx() #设置双坐标轴
plt.plot(x,y2,color='b',label='新利润')
plt.legend(loc='upper right',fontsize=15,facecolor='y',edgecolor='r',shadow=True)
for a,b in zip(x,y2): #zip函数为内置函数,打包成元组
plt.text(a,b,b,fontdict={'family':'KaiTi','color':'c','size':15}) #text函数添加设置数据标签
plt.ylabel('新利润',fontdict={'family':'SimSun','color':'c','size':15},loc='top')
plt.xlim(0,8) #设置x轴取值范围
#plt.axis('off') #隐藏y2的坐标轴
plt.grid(b=True,which='major',color='y',axis='y',linestyle='dashed',linewidth=0.7) #为第二张图的y轴添加网格线
plt.show()

③用xlwings模块绘图:常用图表类型及对应的字符串有柱形图('column_clustered')、条形图('bar_clustered')、折线图('line')、面积图('area')、饼图('pie')、圆环图('doughnut')、散点图('xy_scatter')、雷达图('radar')示例代码如下:

chart=sheet.charts.add(left=200,top=0,width=355,height=200)#设置图表位置和尺寸
chart.set_source_data(sheet['A1:C1'].expand('down')) #读取制图数据
chart.chart_type='radar' #设置雷达图

④制作平滑折线图:重新生成x,y坐标绘图,仍以上数x、y举例,用numpy中arange函数,和scipy中的interpolate绘图,代码如下:

import numpy as np
from scipy import interpolate
xnew=np.arange(1,6,0.1)
x=[1, 2, 3, 4, 5, 6]
y=[1,2,3.4,5,7.9,6.1]
func=interpolate.interp1d(x,y,kind='cubic')
ynew=func(xnew)
plt.plot(xnew,ynew)

⑤为散点图添加线性趋势线或者绘制气泡图,代码如下:

import pandas as pd
from sklearn import linear_model
df=sheet['A1:C1'].expand('down').options(pd.DataFrame,index=0).value
model=linear_model.LinearRegression().fit(df[['x','y']],df['z'])
pred=model.predict(df[['x','y']])
plt.plot(df[['x','y']],pred) #绘制线性趋势线
plt.scatter(df['x'],df['z'],s=df['z']*100,color='r',marker='o',label='开心')
plt.scatter(df['y'],df['z'],s=df['z']*200,color='b',marker='o',label='高兴')
plt.legend(loc='upper left')
plt.title('气泡图与趋势线',fontdict={'family':'Microsoft YaHei','size':20},loc='center')
for a,b,c in zip(df['x'],df['z'],df['y']):
plt.text(a,b,c,ha='left',va='top',fontsize=15,color='c')

⑥制作饼图并分离块、圆环图:

plt.pie(df['x'],labels=df['z'],labeldistance=1,autopct='%.2f%%',pctdistance=0.5,startangle=0,radius=1,explode=[0,0,0.3,0,0],shadow=True,frame=False,
wedgeprops={'width':0.4,'linewidth':2,'edgecolor':'c'}) #wedgeprops设置饼图块宽度、边框粗细、边框颜色


⑦雷达图对比多项指标,代码如下:

df=pd.DataFrame(np.random.randn(5,2),columns=['李白','杜甫'])
cols=['年龄','收入','身高','外貌','家庭'] #指定指标维度
df['性质']=cols
df=df.set_index('性质')
#自定义函数绘制雷达图
def plot_radar(data,feature):
plt.rcParams['font.serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
cols=['年龄','收入','身高','外貌','家庭'] #指定指标维度
colors=['g','r'] #各系列的颜色
angles0=np.linspace(0.1*np.pi,2.1*np.pi,len(cols),endpoint=False) #根据显示指标个数等分圆形
angles=np.concatenate((angles0,[angles0[0]])) #数组拼接
fig=plt.figure(figsize=(8,8)) #设置窗口大小
ax=fig.add_subplot(111,polar=True) #设置图表在窗口显示位置,并设置极坐标系;111表示将画布分成1行1列,并在第1个区域绘制图表
for i,c in enumerate(feature):
stats=data[c] #获取各系列对应指标数据
stats=np.concatenate((stats,[stats[0]])) #连接指标数据
ax.plot(angles,stats,'-',linewidth=6,c=colors[i],label='%s'%(c))#制作雷达图
ax.fill(angles,stats,color=colors[i],alpha=0.25)#为一组坐标值定义的多边形区域填充颜色
ax.legend()
ax.set_yticklabels([]) #隐藏坐标轴数据
ax.set_thetagrids(angles0*180/np.pi,cols,fontsize=16) #添加并设置数据标签(这里为性质标签)
plt.show()
return fig
figure_radar=plot_radar(df,list(df.columns))#调用自定义雷达图

⑧温度计图:双柱形图叠加

#温度计
percentage=0.8
plt.bar(1,1,color='yellow')
plt.bar(1,percentage,color='cyan')
plt.text(1,percentage-0.05,percentage,ha='center',fontdict={'size':20})
plt.xlim(0,2)


文章转载自Gavin的数据分析进阶之路,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论