python - 如何摆脱此错误:ValueError:x 和 y 必须具有相同的第一维,但具有形状 (1,) 和 (8000,)
问题描述
我已经从worldmeter网站上抓取了一些日期,我想将其显示在图表上。然而,它正在出现
ValueError:x 和 y 必须具有相同的第一维,但具有形状 (1,) 和 (8000,)
有人可以帮我修改此代码以使其正常工作。
到目前为止,这是我的代码:
import tkinter as tk #this imports the tkinter library
from tkinter import ttk
from bs4 import BeautifulSoup
import requests
import matplotlib.pyplot as plt
root= tk.Tk()
URL = "https://www.worldometers.info/coronavirus/country/us/"
page = requests.get(URL)
soup = BeautifulSoup(page.content, "html.parser")
results=soup.find_all("div", {"class": "col-md-12"})
data=results[4]
script = data.find('script')
stringCon = script.string
x = stringCon.strip()[291:-9258] #these are the dates i have web scraped that i want on the
x-axis
y=[]
for i in range(0, len(x)):
y.append(i+1) #this for loop is to produce data for the y axis
plt.style.use('seaborn-dark')
plt.plot(x, y, label = "US")
plt.title('Daily Cases')
plt.xlabel('Date')
plt.ylabel('Cases')
plt.grid(True)
plt.legend()
plt.show()
root.mainloop()
错误:
Traceback (most recent call last):
File "C:\Users\teera\OneDrive\Desktop\School\Subjects\Computer Science\Python Practice\Python Scrape\creating graphs.py", line 156, in <module>
plt.plot(x, y, label = "US") #plots the re against the dates and labels the graph as the country's name
File "C:\Users\teera\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\pyplot.py", line 3019, in plot
return gca().plot(
File "C:\Users\teera\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_axes.py", line 1605, in plot
lines = [*self._get_lines(*args, data=data, **kwargs)]
File "C:\Users\teera\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 315, in __call__
yield from self._plot_args(this, kwargs)
File "C:\Users\teera\AppData\Local\Programs\Python\Python39\lib\site-packages\matplotlib\axes\_base.py", line 501, in _plot_args
raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (1,) and (8000,)
解决方案
x
你的变量的元素是字符串(print(type(x[0]))
返回<class 'str'>
),所以 plt 不确定如何解释它。
推荐阅读
- stage - AWS-CDK API-GW 自定义域基本路径映射设置阶段
- r - 在ggplot2中隐藏geom_bar和facet_grid图表中的非顺序类别?
- android - 替换 Tablayout Android 中的片段
- asynchronous - 如何使用异步等待将这个 promise.then 更改为 promise.all?
- awk - 来自脚本参数的 AWK 列?
- android - 如何在 SingleChildScroll 内制作水平滚动 ListView
- kotlin - Dagger 2 Set Multibinding 不适用于 Kotlin 中的 SimpleEntry?
- arm - Arm Mali GPU 中的点积是否比 MAD(乘加)指令更快?
- html - 有没有办法检索网页的最终渲染像素值?
- java - Spring WebFlux 测试抛出“IllegalStateException: Failed to load ApplicationContext”异常