2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for your response. Could you please check my edit?
I think you are missing how to use pandas to plot data, I suggest reading this: datatofish.com/plot-dataframe-pandas
The error occurs in line 17 when plt.subplots(nrows=2, ncols=2). It works for plt.subplots(nrows=1, ncols=2). I looked at the reference you provided, it's used for plotting dataframe columns. please let me know if I am missing something
In that case, axes is 2 dimensional and thus you have to do axes[i][j] i=0,1 j=0,1 @Natasha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.