如何消除此错误: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,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,)
wangyuan986 回答:如何消除此错误:ValueError: x 和 y 必须具有相同的第一维,但具有形状 (1,) 和 (8000,)

您的 x 变量的元素是字符串(print(type(x[0])) 返回 <class 'str'>),因此 plt 不确定如何解释它。

本文链接:https://www.f2er.com/1292.html

大家都在问