Python使用matplotlib可视化模拟商场促销价格关系折线图

可视化模拟商场促销价格关系折线图

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'simhei'
plt.rcParams['axes.unicode_minus']=False

#进价与零售价
basePrice,salePrice = 49,75

#计算购买num个商品时的单价,买的越多,单价越低
def compute(num):
    return salePrice * (1-0.01*num)

#numbers用来存储顾客购买数量
#earns用来存储商场的盈利情况
#totalConsumption用来存储顾客消费总金额
#saves用来存储顾客节省的总金额
numbers = list(range(1,31))
earns = []
totalConsumption = []
saves = []

#根据顾客购买数量计算三组数据
for num in numbers:
    perPrice = compute(num)
    earns.append(round(num*(perPrice-basePrice), 2))#round函数 返回表达式或值保留指定的小数
    totalConsumption.append(round(num*perPrice,2 ))
    saves.append(round(num*(salePrice-perPrice), 2))

#绘制商家盈利和顾客节省的折线图,系统自动分配线条颜色
plt.plot(numbers,earns,label='商家盈利')
plt.plot(numbers,totalConsumption,label='顾客总消费')
plt.plot(numbers,saves,label='顾客节省')

#设置图例
plt.legend()

#设置坐标轴标签文本
plt.xlabel('顾客购买数量(件)')
plt.ylabel('金额(元)')
#设置图形标题
plt.title('数量-金额关系图',fontsize=20)

#计算并标记商家盈利最多的批发数量
maxEarn = max(earns)
bestNumber = numbers[earns.index(maxEarn)]#index()方法用于从列表中找出这个值在列表中第一个匹配出来的索引
#散点图,在相应位置绘制一个红色五角星
plt.scatter(bestNumber,maxEarn,marker='*',color='red',s=120)
#使用annotate()函数在指定位置进行文本标注
plt.annotate(xy=(bestNumber,maxEarn),
             xytext=(bestNumber-1,maxEarn+200),
             s=str(maxEarn),
             arrowprops=dict(arrowstyle="<->"))
plt.show()

最后的效果图:

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值