【问题标题】:Increment x and y values with matplotlib使用 matplotlib 增加 x 和 y 值
【发布时间】:2021-10-05 16:18:38
【问题描述】:

我有这张图表,其中我的 x 和 y 值看起来很乱。我相信这是因为所有的值都聚集在一起,因为它们有 552 个。我将 x 值简化为月份和年份,这样可以更好地分散 x 值,但是我认为这就是图表看起来像楼梯而不是线性的原因:

这是我的代码。我只使用matplotlib 绘制图表,使用SQL 帮助组织this csv 文件中的数据。如何简化我的 x 和 y 值?

from matplotlib import pyplot as plt
from cs50 import SQL
import datetime

def make_list(query, thelist, key): # format list so not dict
    for i in query:
        thelist.append(i[key])
    return thelist

plt.title("Covid Cases")
plt.xlabel("Time")
plt.ylabel("Number of Cases")

# Each date has the countries' case reports

db = SQL("sqlite:///data.db")

# create list of dates for x axis
datesDict = db.execute("SELECT Date FROM countries WHERE Country = 'Afghanistan'")
dates = []
dates = make_list(datesDict, dates, 'Date')
for i in range(len(dates)): # format date
    dates[i] = datetime.datetime.strptime(dates[i], '%Y-%m-%d').strftime("%b %Y")

# create list of confirmed cases
select_country = "United Kingdom"
find_confirmed = db.execute("SELECT Confirmed FROM countries WHERE Country = ?", select_country)
confirmed = []
confirmed = make_list(find_confirmed, confirmed, "Confirmed")

# plot
plt.plot(dates, confirmed, color = "red")
plt.show()

【问题讨论】:

  • 当数据是字符串时会发生这种情况。由于strftime,这里的日期肯定是字符串。将日期保留为实际的 datetime 对象并使用 matplotlib.dates.DateFormatter('%b %Y')
  • 您还应该仔细检查 SQL 结果是字符串还是数字。
  • 非常感谢,它看起来好多了。我应该把matplotlib.dates.DateFormatter('%b %Y')放在哪里?间距现在看起来不错,但显示的是 YYYY-MM,而不是 Jan 2020。

标签: python matplotlib


【解决方案1】:

当数据是字符串时会发生这种情况。

  1. 我不确定 SQL 数据,但根据您的图形输出,它们看起来像字符串。将它们转换为浮点数,例如在make_list 函数中:

    thelist.append(float(i[key]))
    
  2. 由于strftime,日期绝对是字符串,因此删除strftime 以保持日期为真实的datetime 对象:

    for i in range(len(dates)):
        dates[i] = datetime.datetime.strptime(dates[i], '%Y-%m-%d')
    
  3. 在绘图命令后添加DateFormatterautofmt_xdate

    import matplotlib.dates as mdates
    
    plt.plot(dates, confirmed, color='red')
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
    plt.gcf().autofmt_xdate()
    
    plt.show()
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多