1
votes

X axis was inverted automatically and unexpectedly when plotting a series of data against another series of data using pandas. Please look at my code below. How can I ensure x axis is always pointing to the right? Is this automatic inversion of x axis an intended behavior of pandas? Can it be disabled?

Let me explain my example below. Three plots are created. I expect each one shows nearly 45 degree line rising to the right. However, some of them have 45 degree line falling to the right because its x axis is inverted automatically. It appears that whether x axis is inverted or not depends on the values to be plotted.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df2 = pd.DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"])
df3 = df2*1.1

df3.rename(columns={"a": "a*1.1", "b": "b*1.1", "c": "c*1.1"}, inplace=True)
df23 = df2.join(df3)

fig, ax_list = plt.subplots(1,3)

ax=ax_list[0]
df23[["a", "a*1.1"]].plot(ax=ax, x="a")
ax.axis('equal')
ax.set_title("(x,y)=(a,a*1.1)")
print ax.get_xlim()  ## Added for clarity

ax=ax_list[1]
df23[["b", "b*1.1"]].plot(ax=ax, x="b")
ax.axis('equal')
ax.set_title("(x,y)=(b,b*1.1)")
print ax.get_xlim()  ## Added for clarity  

ax=ax_list[2]
df23[["c", "c*1.1"]].plot(ax=ax, x="c")
ax.axis('equal')
ax.set_title("(x,y)=(c,c*1.1)")
print ax.get_xlim()  ## Added for clarity

Created plot

2
I had a similar problem. Try sorting your plots. e.g. df23[["a", "a*1.1"]].sort("a").plot(ax=ax, x="a") - Bob Haffner
Thanks for your comment. I tried sorting. However, sorting changes the shape of curve in case it is a multivalued function. So I want to know a way to disable the inversion of x axis. - user22097
Have you tried using set_xticklabels on x-axis ? - fixxxer
It's not about labeling. To clarify the point, I added ax.get_xlim() in my example code. You should see the left value of the x axis range is larger than the right value. - user22097
There's a similar question asked here - stackoverflow.com/questions/14770218/… - fixxxer

2 Answers

4
votes

I asked this question on the issue tracker of pandas, and got answer.

daraframe.plot(..) is designed such that

  • x coordinate of points is determined based on the index (i.e. row number) of the column specified by x parameter.
  • y coordinate of points is the value of the column specified by y parameter.

For a scatter plot, I think the above design is not suitable. The only solution I can think of is to use plt.plot direclty.

cphlewis's workaround is also useful.

3
votes

You can enforce a direction for each plot:

(t,b)= ax.get_xlim()  ## Added for clarity
if t > b:
    ax.set_xlim((b,t))

or

if ax.xaxis_inverted():
    ax.invert_xaxis()

(the latter just do the explicit three-line version, though.)