Matplotlib 以一种非常奇怪的方式绘制图形
Matplotlib plots graph in a very strange way
正在尝试绘制一天中的紫外线指数。数据来自 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()
您的 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,daily,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()
这解决了所有问题,并且代码不言自明,但请询问您是否对任何事情感到困惑:
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()
(另外,检查你的 weather.csv
文件;它不应该是 csv
格式,因为它是 json 数据,而不是 table 数据。)
正在尝试绘制一天中的紫外线指数。数据来自 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()
您的 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,daily,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()
这解决了所有问题,并且代码不言自明,但请询问您是否对任何事情感到困惑:
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()
(另外,检查你的 weather.csv
文件;它不应该是 csv
格式,因为它是 json 数据,而不是 table 数据。)