ragesz ragesz - 2 months ago 27x
Python Question

Python pandas plot scatter datetime error

I want a scatter plot where x-axis is a

, y-axis is an
. And I have only a few of datapoints that are discrete and not continuous, so I don't want to connect datapoints.

My DataFrame is:

df = pd.DataFrame({'datetime':[dt.datetime(2016,1,1,0,0,0), dt.datetime(2016,1,4,0,0,0),
dt.datetime(2016,1,9,0,0,0)], 'value':[10, 7, 8]})

If I use "normal" plot than I got a "line" figure:

df.plot(x='datetime', y='value')

But how can I plot only the dots? This gives error:

df.plot.scatter(x='datetime', y='value')
KeyError: 'datetime'

Of course I can use some cheat to get the result I want, for example:

df.plot(x='datetime', y='value', marker='o', linewidth=0)

But I don't understand why the
version does not work...

Thank you for help!


Scatter plot can be drawn by using the DataFrame.plot.scatter() method. Scatter plot requires numeric columns for x and y axis. These can be specified by x and y keywords each.

Alternative Approach:

In [71]: df['day'] = df['datetime'].dt.day

In [72]: df.plot.scatter(x='day', y='value')
Out[72]: <matplotlib.axes._subplots.AxesSubplot at 0x25440a1bc88>