user22097
user22097

Reputation: 229

x-axis inverted unexpectedly by pandas.plot(...)

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

Upvotes: 1

Views: 4715

Answers (2)

user22097
user22097

Reputation: 229

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.

Upvotes: 5

cphlewis
cphlewis

Reputation: 16239

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.)

Upvotes: 4

Related Questions