Python & Pandas: Strange behavior when Pandas plot histogram to a specific ax
The problem is that pandas determines which is the active figure by using gcf()
to get the "current figure". When you create several figures in a row, the "current figure" is the last one created. But you are trying to plot to an earlier one, which causes a mismatch.
However, as you can see on line 2954 of the source you linked to, pandas will look for an (undocumented) figure
argument. So you can make it work by doing df['speed'].hist(ax=ax2, figure=fig2)
. A comment in the pandas
source notes that this is a "hack until the plotting interface is a bit more unified", so I wouldn't rely on it for anything too critical.
The other solution is to not create a new figure until you're ready to use it. In your example above, you only use figure 2, so there's no need to create the others. Of course, that is a contrived example, but in a real-life situation, if you have code like this:
fig1, ax1 = plt.subplots(figsize=(4,3))
fig2, ax2 = plt.subplots(figsize=(4,3))
fig3, ax3 = plt.subplots(figsize=(4,3))
something.hist(ax=ax1)
something.hist(ax=ax2)
something.hist(ax=ax3)
You can change it to this:
fig1, ax1 = plt.subplots(figsize=(4,3))
something.hist(ax=ax1)
fig2, ax2 = plt.subplots(figsize=(4,3))
something.hist(ax=ax2)
fig3, ax3 = plt.subplots(figsize=(4,3))
something.hist(ax=ax3)
That is, put each section of plotting code right after the code that creates the figure for that plot.