Python数据分析与挖掘实战代码纠错 代码3-3

本文介绍如何使用Python的pandas和matplotlib库修正并绘制菜品盈利的帕累托图,详细展示了代码调整过程及图表生成步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python数据分析与挖掘实战 代码清单3-3更正
代码清单3-3 菜品盈利帕累托图代码
书上代码如下:

from __future__ import print_function
import pandas as pd

#初始化参数
dish_profit = '../data/catering_dish_profit.xls' #餐饮菜品盈利数据
data = pd.read_excel(dish_profit, index_col = u'菜品名')
data = data[u'盈利'].copy()
data.sort(ascending = False)

import matplotlib.pyplot as plt #导入图像库
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号

plt.figure()
data.plot(kind='bar')
plt.ylabel(u'盈利(元)')
p = 1.0*data.cumsum()/data.sum()
p.plot(color = 'r', secondary_y = True, style = '-o',linewidth = 2)
plt.annotate(format(p[6], '.4%'), xy = (6, p[6]), xytext=(6*0.9, p[6]*0.9), arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) #添加注释,即85%处的标记。这里包括了指定箭头样式。
plt.ylabel(u'盈利(比例)')
plt.show()

直接运行会报错,更改后的代码如下:

from __future__ import print_function
import pandas as pd
import matplotlib.pyplot as plt

dish_profit = 'C:/Users/Qhy/Desktop/catering_dish_profit.xls'
#用菜品名的列作为行索引
data = pd.read_excel(dish_profit,index_col=u'菜品名')
#只用到菜品盈利的数据
data = data[u'盈利'].copy()
#将数据转化为DataFrame类型
data = pd.DataFrame(data)
#根据菜品的盈利从大到小排序
data.sort_values('盈利',ascending=False)

#设置中文标签字体
plt.rcParams['font.sans-serif'] = ['FangSong']
#正常显示负号
plt.rcParams['axes.unicode_minus'] = False

#调用DataFrame的plot方法直接画图
ax1 = data.plot(kind='bar',legend=True)
#设置图像标题
ax1.set_title('帕累托图')
#设置左边y轴名称
plt.ylabel('盈利(元)')
#添加y轴的坐标轴
ax2 = ax1.twinx()
#求累计频率
p = 1.0*data.cumsum()/data.sum()
#ax=ax2 设置两个图形画到同一个坐标轴当中
p.plot(color='r',secondary_y=True,style = '-o',linewidth = 2,ax=ax2)
#设置箭头格式和大小,已经标注的文字
plt.annotate(format(p.ix[6,'盈利'],'.4%'),xy=(6, p.ix[6,'盈利']),xytext=(6*0.9, p.ix[6,'盈利']*0.9),arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.2"))
#设置右边y轴坐标
plt.ylabel('盈利(比例)')
plt.show()

1、要取得p中某一菜品的对应累计频率需要通过同时搜索行索引和列索引得到
2、twinx() 添加新的y轴
3、twiny()添加新的x轴
4、plot()中,ax参数的含义是一个图像切成不同片段,子图对象

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值