Plotting different dataframe data in subplots

Viewed 116

I'm trying to plot data in two dataframes in two subplots. I'm referring to this link

import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt


df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))


plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=2)

df1.plot(ax=axes[0, 0], style='o-')
axes[0, 0].set_xlabel('x')
axes[0, 0].set_ylabel('y')
axes[0, 0].set_title('ttl')

df2.plot(ax=axes[0, 1], style='o-')
axes[0, 1].set_xlabel('x')
axes[0, 1].set_ylabel('y')
axes[0, 1].set_title('ttl')

However, I get the following error

df1.plot(ax=axes[0, 0], style='o-')
IndexError: too many indices for array

Any suggestions on how to resolve this will be really helpful. EDIT: The answer provided below works for 1 row with 2 cols

I'm facing an error for 2 rows and 2 cols

import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt


df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))
df3 = pd.DataFrame(np.random.randn(10, 10))
df4 = pd.DataFrame(np.random.randn(10, 10))

pprint(df1)

plt.figure()
fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0], style='o-')
axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[0].set_title('ttl')

df2.plot(ax=axes[1], style='o-')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')
axes[1].set_title('ttl')


df3.plot(ax=axes[2], style='o-')
axes[2].set_xlabel('x')
axes[2].set_ylabel('y')
axes[2].set_title('ttl')

df4.plot(ax=axes[3], style='o-')
axes[3].set_xlabel('x')
axes[3].set_ylabel('y')
axes[3].set_title('ttl')

plt.show()

Error:

AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'

Any suggestions?

1 Answers

Axes are one dimensional, you have to do like this:

df1.plot(ax=axes[0], style='o-')
df2.plot(ax=axes[1], style='o-')

I suggest reading this, look at the squeeze parameter and you will understand this is happening.

Related