简体   繁体   English

在 matplotlib 中绘制分类数据时避免将字符串解释为日期

[英]Avoid interpreting strings as dates when plotting categorical data in matplotlib

I am trying to plot categorical data in matplotlib with string entries that look like dates but are not dates.我试图用看起来像日期但不是日期的字符串条目在 matplotlib 中绘制分类数据。 Matplotlib tries to automatically convert the string to a datetime object, but fails. Matplotlib 尝试自动将字符串转换为日期时间对象,但失败了。 How can I force matplotlib to treat the categories as strings and prevent it from trying to convert the string to a datetime object?如何强制 matplotlib 将类别视为字符串并防止它尝试将字符串转换为日期时间对象?

Here's my example:这是我的例子:

import matplotlib.pyplot as plt
categories = ['2019-20', '2020-21']
vals = [5, 10]
plt.plot(categories, vals)

Which gives这使

ValueError: could not convert string to float: '2019-20'
<...snip...>
calendar.IllegalMonthError: bad month number 20; must be 1-12

For what it's worth, in my example, the strings represent academic years (2019-2020 and 2020-2021), but matplotlib assumes that they are dates in the form YYYY-MM and throws and error when trying to convert "20" and "21" to a valid month.就其价值而言,在我的示例中,字符串代表学年(2019-2020 和 2020-2021),但 matplotlib 假定它们是 YYYY-MM 形式的日期,并在尝试转换“20”和“ 21" 到有效月份。

If I change the categories to ['2019-2020', '2020-2021'], the code works fine (matplotlib no longer assumes the strings represent a datetime object).如果我将类别更改为 ['2019-2020', '2020-2021'],则代码工作正常(matplotlib 不再假设字符串表示日期时间对象)。

import matplotlib.pyplot as plt
categories = ['2019-2020', '2020-2021']
vals = [5, 10]
plt.plot(categories, vals)

在此处输入图片说明

But I prefer to use the shorter version YYYY-YY rather than the longer YYYY-YYYY.但我更喜欢使用较短的 YYYY-YY 而不是较长的 YYYY-YYYY。

plt.plot will try to do a XY Cartesian coordinate type plot if you pass in two positional args.如果您传入两个位置参数,plt.plot 将尝试执行 XY 笛卡尔坐标类型绘图。 I think you need something like plot(vals) only and then call plt.xticks:我认为你只需要像plot(vals)这样的东西,然后调用 plt.xticks:

import matplotlib.pyplot as plt
import numpy as np
categories = ['2019-20', '2020-21']
vals = [5, 10]
plt.plot(vals)
plt.xticks(np.arange(len(vals)), tuple(categories))

refer to https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xticks.html参考https://matplotlib.org/api/_as_gen/matplotlib.pyplot.xticks.html

While you code works fine in my old version ( matplotlib 2.2.2 ), you can try the following workaround.虽然您的代码在我的旧版本 ( matplotlib 2.2.2 ) 中运行良好,但您可以尝试以下解决方法。 The trick is to use the categories as custom x-ticklabels诀窍是将categories用作自定义 x-ticklabels

import matplotlib.pyplot as plt

categories = ['2019-20', '2020-21']
vals = [5, 10]
plt.plot(range(len(categories)), vals)

plt.xticks(range(len(categories)), categories);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM