3

I am having some trouble understanding the subplot concept. As I understand subplots are organized (number of rows, numbers of column, and the plot number or how many places the plot is taking)

I have this code:

from pandas import util
import pandas.util.testing as testing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl

df = util.testing.makeDataFrame()


with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'light', 'font.size': 12}):
    fig = plt.figure(figsize= (12, 6))

    
    ax = fig.add_subplot(2, 2, (1,2))
    ax2 = ax.twinx()
    df['A'].plot(ax=ax, color = 'g')
    df['B'].plot(ax=ax2, color ='g')

    fig.add_subplot(223)
    df['C'].plot(color='r')
    plt.axvline(x = 7, color = 'b', label = 'axvline - full height')
    
    fig.add_subplot(2,2,4)
    df = df.round(0)
    ax3 = df['D'].plot(kind='bar')
    ax3.legend( prop={'size': 6})

    fig.tight_layout()
    plt.show()

Which produces this plot: enter image description here (1,2) in ax = fig.add_subplot(2, 2, (1,2)) does not say location or plot number, isn't it confusing? This is because ax = fig.add_subplot(2, 2, (3,2)) would mean there are 3 plots and taking 2 places but it throws this error

IndexError: GridSpec slice would result in no space allocated for subplot

Why the error?

1 Answer 1

4

Your interpretation of the tuple (third parameter) is incorrect: ax = fig.add_subplot(2, 2, (3,2)) says 4 subplots (2 rows x 2 columns) with the following indices:

+---+---+
| 1 | 2 |
+---+---+
| 3 | 4 |
+---+---+

and (3, 2) would be a subplot that spans from index # 3 to # 2 which is impossible as they are on a diagonal. (1, 3) would be a subplot on the left over the full hight, (3, 4) at the bottom over the full width etc.

From the docs of subplot:

Three integers (nrows, ncols, index). The subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure.

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

Comments

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.