数据可视化: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()