Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overlay two subplots in the same subplot (matplotlib)

I plotted two different subplots using matplotlib.plt and pandas.DataFrame.plot.

Both figures are stored in the same pandas dataframe, which I called f. You can download the sample data here.

One of these plots cannot be described by a function (that is, one x value can yield two or more y values. This is what's causing the issue (I'm trying to plot a square).

I tried:

f[f['figure'] == 'fig1'].plot(x='x_axis', y='y_axis', legend=False)
f[f['figure'] == 'fig2'].plot(x='x_axis', y='y_axis', legend=False)
plt.show()

Figs

I want both subplots combined into a single one. Is there a way to plot the second subplot in the same subplot as the first? I want to stack both figures in a single subplot.

like image 487
Arturo Sbr Avatar asked Feb 21 '26 04:02

Arturo Sbr


1 Answers

You can always plot again and again into the same plot if you have stored its axes object, e.g. like

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

f[f['figure'] == 'fig1'].plot(ax=ax, x='x_axis', y='y_axis', legend=False)
f[f['figure'] == 'fig2'].plot(ax=ax, x='x_axis', y='y_axis', legend=False)
plt.show()

Note that this is just one single example how to get the current axes - another one might be

ax = plt.gca()

The main point here is to refer to it in pandas' plot command with the ax kwarg.

like image 138
SpghttCd Avatar answered Feb 22 '26 16:02

SpghttCd