Issue
I am trying to plot a subplot inside a subplot:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from pandas import util
import pandas.util.testing as testing
import matplotlib.pyplot as plt
import pandas as pd
df = util.testing.makeDataFrame()
with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'light', 'font.size': 12}):
fig = plt.figure(figsize= (12, 6), dpi =200)
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()
I am trying to get access to fig.add_subplot(223)
so I can insert this code, which will allow me to plot another subplot inside the subplot.
fig = plt.figure(dpi =200)
fig.subplots_adjust(hspace= 0)
ax5 = fig.add_subplot(3,1,(1,2))
df['A'].plot(color='r')
plt.axvline(x = 7, color = 'b', label = 'axvline - full height')
ax6 = fig.add_subplot(3,1,(3) , sharex = ax5)
df['A'].plot(color='r')
So that this can go instead of figure (223)
Could you please advise what I am missing in the hierarchy? As in the main fig
has subplots, how can I declare another fig inside the subplot?
Solution
You can use a subplotspec
for this kind of nested layout:
import matplotlib.pyplot as plt
import matplotlib as mpl
from pandas import util
df = util.testing.makeDataFrame()
with mpl.rc_context(rc={'font.family': 'serif', 'font.weight': 'light', 'font.size': 12}):
fig = plt.figure(figsize=(12, 6), dpi=200)
gs = fig.add_gridspec(2, 2)
sgs = gs[1, 0].subgridspec(2, 1, hspace=0, height_ratios=[2, 1])
ax1 = fig.add_subplot(gs[0, :])
ax1_twinned = ax1.twinx()
df['A'].plot(ax=ax1, color='g')
df['B'].plot(ax=ax1_twinned, color='g')
ax2 = fig.add_subplot(gs[1, 1])
df = df.round(0)
df['D'].plot(kind='bar', ax=ax2)
ax2.legend( prop={'size': 6})
ax3 = fig.add_subplot(sgs[0])
df['A'].plot(color='r', ax=ax3)
ax3.axvline(x=7, color='b', label='axvline - full height')
ax4 = fig.add_subplot(sgs[1], sharex=ax3)
df['A'].plot(color='r', ax=ax4)
fig.tight_layout()
plt.show()
Answered By - Stef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.