【问题标题】:Graph works fine in Jupyter notebook but not pycharm图形在 Jupyter 笔记本中运行良好,但在 pycharm 中运行良好
【发布时间】:2021-07-17 02:26:09
【问题描述】:

尝试在 python 中创建可视化,虽然它适用于 jupyter notebook,但我无法在实际 IDE 中获得我想要的输出。这种情况发生在其他人身上吗?两者的代码完全相同。 jupyter 在 1 个单元格中运行(实际上只是复制和粘贴)。

PyCharm:

Jupyter:

import pandas as pd
from matplotlib import pyplot as plt #also tried import matplotlib.pyplot as plt
from datetime import date, timedelta


fig = plt.figure(figsize=(12, 7))
df = pd.read_csv('https://raw.githubusercontent.com/datasets/covid-19/main/data/countries-aggregated.csv',
                     parse_dates=['Date'])
yesterday = date.today() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
today_df = df[df['Date'] == yesterday]
top_10 = today_df.sort_values(['Confirmed'], ascending=False)[:10]
top_10.loc['rest-of-world'] = today_df.sort_values(['Confirmed'], ascending=False)[10:].sum()
top_10.loc['rest-of-world', 'Country'] = 'Rest of World'
ax = fig.add_subplot(111)
ax.pie(top_10['Confirmed'], labels=top_10['Country'], autopct='%1.1f%%')
ax.title.set_text('Hardest Hit Countries Worldwide')
plt.legend(loc='upper left')
plt.show()

【问题讨论】:

  • IDE 是开发代码的唯一工具——开发后你可以在没有IDE 的情况下运行代码——所以更重要的是它是否可以直接在控制台/终端python script.py 中运行。也许当您在控制台中运行它时,它会显示一些错误消息,可以帮助您查看问题。

标签: python matplotlib pycharm


【解决方案1】:

我在没有IDE 的情况下测试了代码,它给了我同样错误的情节。

它还在ax.pie()中显示它需要normalize=True所以我添加了它。

但它仍然没有解决主要问题。

如果您使用print() 来查看变量中的值,那么您可能会看到空的today_df,它会生成错误的绘图。

首先你忘了yesterday.strftime('%Y-%m-%d')

 yesterday = yesterday.strftime('%Y-%m-%d')

但最奇怪的问题是我的时区。我住在yesterday 给出的日期在CSV 中尚不存在的地方,我不得不使用timedelta(days=2)(前天)来获取一些数据并查看情节。 也许几个小时后他们会更新CSV 中的数据,timedelta(days=1) 会工作几个小时 - 稍后它会再次出现同样的问题,等等。

更好的使用

yesterday = max(df['Date'])

获取最新数据。


import pandas as pd
from matplotlib import pyplot as plt
from datetime import date, timedelta

url = 'https://raw.githubusercontent.com/datasets/covid-19/main/data/countries-aggregated.csv'

fig = plt.figure(figsize=(12, 7))
df = pd.read_csv(url, parse_dates=['Date'])

#yesterday = date.today() - timedelta(days=2)
#yesterday = yesterday.strftime('%Y-%m-%d')

yesterday = max(df['Date'])

print('yesterday:', yesterday)

today_df = df[df['Date'] == yesterday]

print(today_df)

top_10 = today_df.sort_values(['Confirmed'], ascending=False)[:10]
top_10.loc['rest-of-world'] = today_df.sort_values(['Confirmed'], ascending=False)[10:].sum()
top_10.loc['rest-of-world', 'Country'] = 'Rest of World'
ax = fig.add_subplot(111)

ax.pie(top_10['Confirmed'], labels=top_10['Country'], autopct='%1.1f%%', normalize=True)

ax.title.set_text('Hardest Hit Countries Worldwide')
plt.legend(loc='upper left')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    相关资源
    最近更新 更多