【问题标题】:problem in plotting multiple lists using matplotlib使用 matplotlib 绘制多个列表的问题
【发布时间】:2020-05-03 16:36:42
【问题描述】:

我正在编写一个脚本,可用于绘制国家明智的 covid 时间序列数据。当我绘制一个国家/地区时它工作正常,但 Y 轴的比例打印得当。 Plot which I am getting 问题是在打印一个国家的最大值后,用较小的值外推 y 轴以绘制后续国家的数据点。 我的脚本代码如下

import requests
from contextlib import closing
import csv
import matplotlib.pyplot as plt
url = "https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv"

def prepareCountryWiseData(country):
    countryWise = {}
    with closing(requests.get(url, stream=True)) as r:
        f = (line.decode('utf-8') for line in r.iter_lines())
        reader = csv.reader(f, delimiter=',', quotechar='"')
        active = []
        recovered = []
        dates = []
        for row in reader:    
             if row[1] == country:
                     dates.append(row[0])
                     active.append(row[2])
                     recovered.append(row[3])
        return (dates, active, recovered)

def plotCountryWiseData(countryList):
    plotable = []
    for country in countryList:
            dates,active,recovered = (prepareCountryWiseData(country))
            plt.plot(active)                
    plt.ylabel('active_cases')
    plt.legend(countryList)
    plt.show()
    plotCountryWiseData(['India','US','Italy'])

【问题讨论】:

  • 这个项目可以使用 pandas 模块吗?
  • 我没用过 pandas 。现在我设法找到了解决这个问题的方法。我已经对这些值进行了四舍五入,matplotlib 已经自动处理了它。但我不知道是否存在一些技术解决方案。如果您知道它使用 pandas,请分享您的想法,这将很有帮助。

标签: python matplotlib data-visualization


【解决方案1】:

如果您可以使用pandas 模块,您的工作会轻松很多:

import pandas as pd, matplotlib.pyplot as plt

url = "https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv"
df = pd.read_csv(url)

fig,ax = plt.subplots()

for k,g in df[df['Country'].isin(['India','US','Italy'])].groupby('Country'):
    ax = g.plot(ax=ax,kind='line',x='Date',y='Confirmed',label=k) 

plt.gcf().suptitle('Active Cases')
plt.show()

结果:

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2017-09-30
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    相关资源
    最近更新 更多