微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Matplotlib 以一种非常奇怪的方式绘制图形

如何解决Matplotlib 以一种非常奇怪的方式绘制图形

尝试绘制一天中的紫外线指数。数据来自一个 api,经过一些处理后,它为我提供了一个不错的列表中的数据。不过剧情实在是太恶心了。 Link to graph。 Y轴的值被重复抛来抛去,所以出现了多个0,多个0的两边都是正数,解释的噩梦。提前致谢

代码

import requests
import re
from matplotlib import pyplot as plt
import numpy as np

# Get weather information
response = requests.get("https://api.openweathermap.org/data/2.5/onecall?lat=55.583328&lon=13.0&lang=se&exclude=minutely,daily,alerts&units=metric&appid=0f0212703cfecb4699dfc2c7edde950a")

# Save weather information to file
with open("weather.csv",'w') as file:
    file.write(response.text)

# Opens the file and gets all the values of "uv-index"
with open("Weather.csv",'r') as text:
    pattern = 'uvi":(.*?),'
    Line = text.read()
    substring = np.array(re.findall(pattern,Line))

# Creates an x-axis as a list with the same size as y-axis
# If they're not the same size,error is given:
# ValueError: x and y must have same first dimension,but have shapes (12,) and (49,)
x_axis = []
for i in range(len(substring)):
    x_axis.append(i)
x_axis = np.array(x_axis)

# Determines size and plots graph
fig,ax = plt.subplots(figsize=(10,6))
ax.plot(x_axis,substring)

# Creates labels
plt.title("UV-Index today")
plt.xlabel("Time")
plt.ylabel("UV-Index")

# Saves the plot as image and shows it on screen
plt.savefig("UV-Index" + ".png")
plt.show()

解决方法

这解决了所有问题,代码一目了然,但请询问您是否对任何事情感到困惑:

import requests
import re
from matplotlib import pyplot as plt
import numpy as np
import json

response = requests.get("https://api.openweathermap.org/data/2.5/onecall?lat=55.583328&lon=13.0&lang=se&exclude=minutely,daily,alerts&units=metric&appid=0f0212703cfecb4699dfc2c7edde950a")

with open("weather.txt",'w') as file:
    file.write(response.text)

# this converts the JSON as a string to JSON as a dictionary
dict1 = json.loads(response.text)

y_axis = []
for entry in dict1['hourly']:
    y_axis.append(entry['uvi'])

y_axis = np.array(y_axis)
x_axis = np.array(range(len(x_axis)))

fig,ax = plt.subplots(figsize=(10,6))
ax.plot(x_axis,y_axis)

plt.title("UV-Index today")
plt.xlabel("Time (Hours)")
plt.ylabel("UV-Index")

plt.savefig("UV-Index" + ".png")
plt.show()

uv graph

(另外,检查您的 weather.csv 文件;它不应该是 csv 格式,因为它是 json 数据,而不是表数据。)

,

您的 substring 是一个字符串列表。 Matplotlib 将字符串视为离散值(因此“0”和“0.01”以及“0”和“1000”之间的距离没有差异;并且它们之间没有顺序,因此“1000”可能看起来低于“0”)。

在绘图前将您的 substring 转换为浮动:

substring = list(map(float,substring))

或者,因为您的子字符串是一个 numpy 数组:

substring = substring.astype('float')
,

如前所述,您的 Y 数据不是数字类型。

这绝对是一种解析 json 响应的新方法。试试这个:

import json
s = json.loads(response.text)
df = pd.json_normalize(s['hourly'])
df['dt'] = pd.to_datetime(df['dt'],unit='s')
df.plot(x="dt",y='uvi')
# Creates labels
plt.title("UV-Index today")
plt.xlabel("Time")
plt.ylabel("UV-Index")
plt.show()

根据要求,完整示例。不确定为什么将结果保存到文本文件中,但它是 json 文件而不是 csv 文件。

import requests
from matplotlib import pyplot as plt
import json
import pandas as pd
import numpy as np

# Get weather information
response = requests.get("https://api.openweathermap.org/data/2.5/onecall?lat=55.583328&lon=13.0&lang=se&exclude=minutely,alerts&units=metric&appid=0f0212703cfecb4699dfc2c7edde950a")

# Save weather information to file
with open("weather.json",'w') as file:
    file.write(response.text)

# Evaluate JSON string to JSON object
s = json.loads(response.text)

# Create DataFrame with hourly data
df = pd.json_normalize(s['hourly'])

# Convert time stamps to actual datetime values
df['dt'] = pd.to_datetime(df['dt'],unit='s')

# Determines size and plots graph
df.plot(x="dt",y='uvi',figsize=(10,6))

# Creates labels
plt.title("UV-Index today")
plt.xlabel("Time")
plt.ylabel("UV-Index")

# Saves the plot as image and shows it on screen
plt.savefig("UV-Index" + ".png")
plt.show()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。