开发者

Plot with non-numerical data on x axis (for ex., dates)

开发者 https://www.devze.com 2023-03-26 18:10 出处:网络
I\'d like to plot numerical data against non numerical data, say something like this: import matplotlib.pyplot as pl

I'd like to plot numerical data against non numerical data, say something like this:

import matplotlib.pyplot as pl
x=['a','b','c','d']
y=[1,2,3,4]
pl.plot(x,y)

However, with matplotlib plot packages you get a warning that the data is not float (ValueError: invalid literal for float(): a).

In their 'How-to', they suggest to put first the numerical data on开发者_开发技巧 the x axis and then format it. Is there a way to do it directly (as above)?


Use the xticks function.

import matplotlib.pyplot as pl
xticks=['a','b','c','d']
x=[1,2,3,4]
y=[1,2,3,4]
pl.plot(x,y)
pl.xticks(x,xticks)
pl.show()


import matplotlib.pyplot as plt
x = ['a','b','c','d']
y = [1,2,3,4]
plt.plot(y)
plt.xticks(range(len(x)), x)
plt.show()

Plot with non-numerical data on x axis (for ex., dates)

On a side note, dates are numerical in this sense (i.e. they have an inherent order and spacing).

Matplotlib handles plotting temporal data quite well and very differently than the above example. There's an example in the matplotlib examples section, but it focuses on showing off several different things. In general, you just use either plot_date or just plot the data and call ax.xaxis_date() (or yaxis_date) to tell matplotlib to use the various date locators and tickers.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号