Show Sidebar Hide Sidebar

Subplots in matplotlib

How to make subplots in matplotlib. Seven examples of stacked, custom-sized, and gridded subplots.

import matplotlib.pyplot as plt


import plotly.plotly as py
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

fig = plt.figure()

ax1 = fig.add_subplot(221)
ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')

ax2 = fig.add_subplot(222)
ax2.plot([1,2,3,4], [1,4,9,16], 'k-')

ax3 = fig.add_subplot(223)
ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')

ax4 = fig.add_subplot(224)
ax4.plot([1,2,3,4], [0,0,1,1], 'g-')


plt.tight_layout()
fig = plt.gcf()

plotly_fig = tls.mpl_to_plotly( fig )
plotly_fig['layout']['title'] = 'Simple Subplot Example Title'
plotly_fig['layout']['margin'].update({'t':40})

plot_url = py.plot(plotly_fig, filename='mpl-simple-subplot')
import matplotlib.pyplot as plt
from matplotlib import gridspec

import plotly.plotly as py
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

fig = plt.figure()
gs = gridspec.GridSpec(3, 3)
ax1 = fig.add_subplot(gs[0,:])
ax1.plot([1,2,3,4,5], [10,5,10,5,10], 'r-')
ax2 = fig.add_subplot(gs[1,:-1])
ax2.plot([1,2,3,4], [1,4,9,16], 'k-')
ax3 = fig.add_subplot(gs[1:, 2])
ax3.plot([1,2,3,4], [1,10,100,1000], 'b-')
ax4 = fig.add_subplot(gs[2,0])
ax4.plot([1,2,3,4], [0,0,1,1], 'g-')
ax5 = fig.add_subplot(gs[2,1])
ax5.plot([1,2,3,4], [1,0,0,1], 'c-')
gs.update(wspace=0.5, hspace=0.5)

fig = plt.gcf()

plotly_fig = tls.mpl_to_plotly( fig )
plotly_fig['layout']['title'] = 'Subplots with variable widths and heights'
plotly_fig['layout']['margin'].update({'t':40})

plot_url = py.plot(plotly_fig, filename='mpl-subplot-variable-width')
import matplotlib.pyplot as plt


import plotly.plotly as py
import plotly.tools as tls
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

t = np.arange(0.01, 5.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.exp(-t)
s3 = np.sin(4*np.pi*t)

ax1 = plt.subplot(311)
plt.plot(t, s1)
plt.setp(ax1.get_xticklabels(), fontsize=6)

# share x only
ax2 = plt.subplot(312, sharex=ax1)
plt.plot(t, s2)
# make these tick labels invisible
plt.setp(ax2.get_xticklabels(), visible=False)

# share x and y
ax3 = plt.subplot(313, sharex=ax1, sharey=ax1)
plt.plot(t, s3)
plt.xlim(0.01, 5.0)
fig = plt.gcf()

plotly_fig = tls.mpl_to_plotly(fig)
plot_url = py.plot(plotly_fig)
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.