数据可视化:matplotlib绘制 天气折线图 显示中文 刻度标签偏转

本文展示如何使用Matplotlib库绘制包含中文刻度标签的天气折线图,并通过旋转中文标签来提高图表的可读性。示例代码中,我们从JSON文件中读取了连续几天的天气数据,包括日期、天气状况、早晚温度等信息,然后利用正则表达式提取数据并将其转换为可绘图的格式。最后,我们设置了图表样式、标题、图例和轴标签,实现了天气数据的可视化。

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

数据可视化:matplotlib绘制 天气折线图 显示中文 刻度标签偏转

结果:

在这里插入图片描述

数据:

{“day”: [“11日(今天)”], “weather”: [“多云”], “sT”: [“0”], “xT”: [“18”]},
{“day”: [“12日(明天)”], “weather”: [“多云”], “sT”: [“31”], “xT”: [“17”]},
{“day”: [“13日(后天)”], “weather”: [“多云”], “sT”: [“32”], “xT”: [“18”]},
{“day”: [“14日(周三)”], “weather”: [“晴”], “sT”: [“32”], “xT”: [“14”]},
{“day”: [“15日(周四)”], “weather”: [“晴”], “sT”: [“34”], “xT”: [“15”]},
{“day”: [“16日(周五)”], “weather”: [“多云转晴”], “sT”: [“37”], “xT”: [“18”]},
{“day”: [“17日(周六)”], “weather”: [“多云”], “sT”: [“33”], “xT”: [“16”]},

代码:

import matplotlib.pyplot as plt
import numpy as np
import re

#显示中文
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False

text = open("G:\python\程序\SpiderDate\Scrapy_Weather\weather.json",'r',encoding='utf-8').read()

day = re.findall(r'{"day": \["(.*?)"\],.*', text)
weather = re.findall(r'{.*"weather": \["(.*?)"\],.*},', text)
sT = re.findall(r'{".* "sT": \["(.*?)"\],.*},', text)
xT = re.findall(r'{.*"xT": \["(.*?)"\]},', text)

sT = list(map(int,sT))
xT = list(map(int,xT))
x = np.arange(len(sT))
#这个是为设置轴刻度做准备
x1 = x.copy()
sT[0]=30


plt.style.use("ggplot")
plt.figure(figsize=[5,5])
plt.subplot()
plt.title("ShiZhan_Weather_plot")
plt.plot(x, sT,c="r")
plt.plot(x, xT,c="g")
plt.legend(["上午","下午"],loc=0)


#显示数据标签
def weather_print(i):
        return weather[i]

for x,sT,xT in zip(x,sT,xT):
    plt.text(x,xT+(sT-xT)/2,"%s"%weather_print(x),ha="center")

#设置轴标签
plt.xlabel("Day")
plt.ylabel("Temp")

#设置轴刻度
plt.xticks(x1,day,rotation=17 )

plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值