matplotlib实现双柱图

1,读取txt文件实现数据可视化
2,txt文件如下图

姓名,语文,数学,英语
小米,98,100,20
小明,100,20,98
小黑,78,98,100

3,代码如下

import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
plt.rcParams['font.family']='SimHei'
plt.rcParams['font.sans-serif']=['SimHei']

# 定义x轴
x = []
# 定义y轴
total_y = []
avg_y = []


list_all = []

# 读取文件
file = open('student.txt','r',encoding='UTF-8').readlines()
for msg in range(1,4):
    student_info = file[msg].replace("\n","")
    stu_list = student_info.split(",")
    list_all.append(stu_list)
print(list_all)
for stu in range(3):
    x.append(list_all[stu][0])
    total_y.append(int(list_all[stu][1])+int(list_all[stu][2])+int(list_all[stu][3]))
    avg_y.append((int(list_all[stu][1]) + int(list_all[stu][2]) + int(list_all[stu][3]))//3)
print(x)
print(total_y)
print(avg_y)
# 每个柱形图的宽度
width = 0.2
plt.bar([x for x in range(3)],total_y,width=width,label='总分',color='r')
# plt.bar(位置,数据,柱形图的大小,图注)
plt.bar([width+x for x in range(3)],avg_y,width=width,label='平均分',color='g')

plt.xticks([x+width/2 for x in range(3)],x)
plt.xlabel('姓名')
plt.ylabel('分数')
plt.legend()
plt.show()

效果如下
在这里插入图片描述

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
使用 Matplotlib 实现动态折线图可以通过以下步骤实现: 1. 导入必要的库,如 Matplotlib 和 NumPy。 ```python import matplotlib.pyplot as plt import numpy as np ``` 2. 创建一个 Figure 对象和一个 Axes 对象,并设置一些基本参数。 ```python fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(0, 10) line, = ax.plot([], []) ``` 3. 定义一个函数,用于更新数据和折线图。该函数接受一个参数表示当前时间,根据时间生成一些随机数据,并更新折线图。 ```python def update(t): x = np.linspace(0, 10, 100) y = np.sin(x - t) + np.random.normal(0, 0.1, size=(100,)) line.set_data(x, y) ``` 4. 使用 FuncAnimation 函数创建一个动画对象,并指定更新函数和帧数。 ```python from matplotlib.animation import FuncAnimation ani = FuncAnimation(fig, update, frames=np.linspace(0, 10, 100), interval=50) ``` 5. 调用 plt.show() 函数显示动态折线图。 ```python plt.show() ``` 完整的代码如下所示: ```python import matplotlib.pyplot as plt import numpy as np from matplotlib.animation import FuncAnimation fig, ax = plt.subplots() ax.set_xlim(0, 10) ax.set_ylim(-2, 2) line, = ax.plot([], []) def update(t): x = np.linspace(0, 10, 100) y = np.sin(x - t) + np.random.normal(0, 0.1, size=(100,)) line.set_data(x, y) ani = FuncAnimation(fig, update, frames=np.linspace(0, 10, 100), interval=50) plt.show() ``` 该代码会生成一个动态折线图,每隔 50 毫秒更新一次,总共更新 100 帧,折线的形状会随着时间变化而变化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java庞

你的鼓励就是我们最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值