【问题标题】:How do I get rid of this error: ValueError: x and y must have same first dimension, but have shapes (1,) and (8000,)如何摆脱此错误:ValueError:x 和 y 必须具有相同的第一维,但具有形状 (1,) 和 (8000,)
【发布时间】:2021-08-01 16:36:33
【问题描述】:

我从 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,)

【问题讨论】:

    标签: python matplotlib web-scraping beautifulsoup graph


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2016-11-10
      相关资源
      最近更新 更多