Python绘制折线图:无需Matplotlib,直接从数据库获取数据
你可以使用Python的PIL库来绘制折线图并保存图片到程序目录中。以下是一个示例代码,可供参考:
import pymysql
from PIL import Image, ImageDraw
# 连接数据库
conn = pymysql.connect(
host='103.214.173.233',
port=3306,
user='water',
password='xX300400',
database='water'
)
# 获取数据库中的体重信息
cursor = conn.cursor()
sql = "SELECT UNIX_TIMESTAMP(data), tizhong FROM tizhongrou"
cursor.execute(sql)
data = cursor.fetchall()
# 关闭数据库连接
cursor.close()
conn.close()
# 转换时间戳为时间和体重数据
timestamps = [int(row[0]) for row in data]
weights = [float(row[1]) for row in data]
# 创建空白图像
width = 800
height = 400
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
# 计算时间和体重的最大最小值
min_timestamp = min(timestamps)
max_timestamp = max(timestamps)
min_weight = min(weights)
max_weight = max(weights)
# 绘制折线图
for i in range(len(timestamps)):
x = int((timestamps[i] - min_timestamp) * width / (max_timestamp - min_timestamp))
y = int((weights[i] - min_weight) * height / (max_weight - min_weight))
draw.ellipse((x-2, y-2, x+2, y+2), fill=(255, 0, 0))
if i > 0:
draw.line((x_prev, y_prev, x, y), fill=(0, 0, 0))
x_prev = x
y_prev = y
# 保存图片
image.save("折线图.png")
注意,上述代码中使用了PIL库来创建图像并绘制折线图。在运行代码之前,请先确保你已经安装了PIL库(可以使用pip install pillow
命令进行安装)。

原文地址: http://www.cveoy.top/t/topic/77B 著作权归作者所有。请勿转载和采集!