4

I'm trying to get a better understanding of how figure, axes, and plt all fit together when combining Matplotlib and Pandas for plotting. The accepted answer here helped me connect Matplotlib and Pandas in an object oriented way I understand through this line:

fig, ax = plt.suplots()
df.plot(ax=ax)

But as I'm diving deeper the answer here threw me off. Specifically, I still have methods I need to call directly off plt, that don't apply to either a figure or an axis. Example:

fig, ax = plt.subplots()

df[['realgdp','trend']]["2000-03-31":].plot(figsize=(8,8), ax=ax)
ax.set_title('Real GDP & Trend')
ax.set_ylabel('Readl GDP')

plt.xticks(rotation=45)

If I try to call xticks(rotation=45) off ax or fig I get an error that neither ax nor fig have an xticks method. The solution I have above works, but I don't understand why.

When I type plt.xticks(rotations=45), where does that information get sent? Why does the comment in the answer here that "when you use the functions available on the module pyplot you are plotting to the 'current figure' and 'current axes'" not apply in this case? Why do I need to call off plt directly?

DavidG
  • 24,279
  • 14
  • 89
  • 82
BLimitless
  • 2,060
  • 5
  • 17
  • 32

1 Answers1

2

plt.xticks() only works on the "current" ax. You should use ax.set_xticks(), ax.set_xticklabels() and ax.tick_params() instead.

plt.xticks() is a rather old function that is still supported, mimicking similar matlab code, born in a time when people were only plotting onto a single plot. The newer functions are more general with more options.

In short: you don't need to call plt directly, you are invited to use the ax functions instead. When calling plt.xticks(), it gets rerouted to the currently active ax (often the last one created).

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • This filled in the missing dots for me. I was able to replace plt.xticks(rotation=45) with ax.tick_params(axis='x', rotation=45). And now I can intertwine pandas and Matplotlib in a happy, sensical, object-oriented way. Thank you! – BLimitless Feb 28 '21 at 23:11