Search code examples
pythonpandasmatplotlibplotaxis-labels

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: enter image description here

But, the above graph does not show the trend correctly. I want this: enter image description here

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.


Solution

  • You need to set_index

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

    enter image description here