piRSquared
piRSquared

Reputation: 294258

axhline affecting plot axis

I'm experimenting with axhline and I'm finding unpredictable behavior. When I add an axhline sometimes it completely messes up my x-axis sometimes it does not.

Setup

import matplotlib.pyplot as plt
import pandas as pd

idx = pd.date_range('2016-01-01', '2016-03-31')
ts = pd.Series([0. for d in idx], index=idx)
t1 = ts['2016-01'] + 1
t2 = ts['2016-02'] + 2
t3 = ts['2016-03'] + 3

First test plot

enter image description here

Exactly as I wanted it.

Problem

Now let's add an axhline

ax = ts.plot()
ax.axhline(y=1.5)
t1.plot(ax=ax)
t2.plot(ax=ax)
t3.plot(ax=ax)
plt.ylim([-1, 4]);

enter image description here

Not at all what I was expecting!

However

If I add the axhline at the end.

ax = ts.plot()
t1.plot(ax=ax)
t2.plot(ax=ax)
t3.plot(ax=ax)
ax.axhline(y=1.5)
plt.ylim([-1, 4]);

enter image description here

No problems.

WHY!?

Why would the order in which I plot dictate the scale of the x-axis?

Versions

import matplotlib
print pd.__version__
print matplotlib.__version__

0.18.0
1.5.1

Upvotes: 3

Views: 2721

Answers (1)

Andreas Hsieh
Andreas Hsieh

Reputation: 2150

There is nothing wrong in the "Problem" plot. You just need to rescale x-axis so that the time scale starts in 2016. If you look at the "Problem" plot very closely then you will see there are three dots at the right end of the plot.

A quick way to fix it:

ax = ts.plot()
ax.axhline(y=1.5)
t1.plot(ax=ax)
t2.plot(ax=ax)
t3.plot(ax=ax)
plt.autoscale()
plt.ylim([-1, 4])
plt.show()

Seems like in pyplot if you create axhline first, you have to rescale before you do plt.show().

Upvotes: 4

Related Questions