简体   繁体   中英

Python pandas line plot: change x-axis to be linear

I have a pandas dataframe which looks like:

df.x = [2, 4, 16, 256]

df.y = [1,2,4,16]

I would like to do a line plot with linear x-axis, although the x values are not linear.

Currently if I plot this dataframe as df.plot(), I get this because the x values are not linear: 在此处输入图片说明

But, the above graph does not show the trend correctly. I want this: 在此处输入图片说明

Note that the X-axis ticks and labels are linear, though the values are not.

How can I plot the graph correctly? I tried renaming the xticklabels but it did not work.

Your index ( X axis) seems to be of object (string) dtype) - convert it to numeric dtype before plotting.

Demo:

In [99]: df.index.dtype
Out[99]: dtype('O')   # <----- NOTE !

plotting original DF:

In [100]: df.plot()
Out[100]: <matplotlib.axes._subplots.AxesSubplot at 0xe74e278>

在此处输入图片说明

let's convert index to numeric dtype and plot it again:

In [101]: df.set_index(pd.to_numeric(df.index, errors='coerce')).plot()
Out[101]: <matplotlib.axes._subplots.AxesSubplot at 0xadd94e0>

在此处输入图片说明

You need to set_index

df.set_index('x').y.plot()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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