matplotlib scatter 不能使用时间作为 x 轴? [英] matplotlib scatter cannot use time as x axis?

查看:124
本文介绍了matplotlib scatter 不能使用时间作为 x 轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用matplotlib,scatter来画图,用时间作为x asix.一个例子是这样的:

I need to use matplotlib, scatter to draw a figure, which uses time as x asix. An example is like this:

t=pd.DataFrame({'Time':pd.to_datetime(['07:42:34','08:01:20','10:12:32','14:20,37','18:36:27']).time,
                'Num':[3,3,3,3,3]})

当我使用以下代码画一条线时:

When I draw a line using the following code:

plt.plot(t.loc[:,'Time'],t.loc[:,'Num'])
plt.show()

这个图看起来不错:

但是如果我用下面的代码来画散点图:

But if I use the following code to draw a scatter figure:

plt.scatter(t.loc[:,'Time'],t.loc[:,'Num'])
plt.show()

然后我有以下错误信息:

Then I have the following error information:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Python35\lib\site-packages\matplotlib\pyplot.py", line 3378, in      scatter
    edgecolors=edgecolors, data=data, **kwargs)
  File "C:\Python35\lib\site-packages\matplotlib\__init__.py", line 1717, in inner
    return func(ax, *args, **kwargs)
  File "C:\Python35\lib\site-packages\matplotlib\axes\_axes.py", line 4032, in scatter
    alpha=alpha
  File "C:\Python35\lib\site-packages\matplotlib\collections.py", line 878, in __init__
    Collection.__init__(self, **kwargs)
  File "C:\Python35\lib\site-packages\matplotlib\collections.py", line 149, in __init__
    offsets = np.asanyarray(offsets, float)
  File "C:\Python35\lib\site-packages\numpy\core\numeric.py", line 544, in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
TypeError: float() argument must be a string or a number, not 'datetime.time'

我对为什么会发生这种情况以及如何使用时间作为x轴绘制散点图感兴趣.我只想要时间,没有日期.

I am interested in why this happens and how to draw a scatter graph using time as x axis. I want just time, no date.

推荐答案

DataFrame.plot 在绘制线条时正确处理日期时间,但在其他类型的绘图(如 bar)上往往会出现问题散点图

DataFrame.plot deals with datetime properly when plotting lines, but tends to have issues with other types of plots like bar and scatterplot

一种便宜且简单的解决方法是仅使用 kind ='line'(默认设置)并将线宽设置为零并指定标记.

A somewhat cheap and simple workaround is to just use kind='line' (which is default) and set the linewidth to zero and specify a marker.

t.plot(x='Time', y='Num', lw=0, marker='o', figsize=(8,4)) 

这篇关于matplotlib scatter 不能使用时间作为 x 轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆