'Inconsistent indexing of subplots returned by `pandas.DataFrame.plot` when changing plot kind
I know that, this issue is known and was already discussed. But I am encountering a strange behaviour, may be someone has idea why: When I run this:
plot = df.plot(kind="box", subplots=True, layout= (7,4), fontsize=12, figsize=(20,40))
fig = plot[0].get_figure()
fig.savefig(str(path) + "/Graphics/" + "Boxplot_all.png")
plot
It works just fine.
When I change the kind plot to ="line", it gives that known error... but why? I don't get it...
plot = df.plot(kind="line", subplots=True, layout= (7,4), fontsize=12, figsize=(20,40))
fig = plot[0].get_figure()
fig.savefig(str(path) + "/Graphics/" + "Line_all.png")
plot
Thanks for your ideas and hints. Cheers Dave
Solution 1:[1]
This seems to be an inconsistency in Pandas. According to their docs, indeed, the DataFrame
's method .plot()
should return
matplotlib.axes.Axes
ornumpy.ndarray
of them
This is true if you choose the kind="line"
option:
>>> df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
columns=['a', 'b', 'c'])
>>> plot=df.plot(subplots=True, layout=(2,2),kind="line")
>>> type(plot)
numpy.ndarray
>>> plot.shape
(2, 2)
But not with kind="box"
, where you get a pandas Series:
>>> plot=df.plot(subplots=True, layout=(2,2),kind="box")
>>> type(plot)
pandas.core.series.Series
>>> plot.shape
(3,)
So, if using kind="line"
, you have to access a 2D array, so you should use:
fig = plot[0,0].get_figure()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | David |