Reputation: 783
I'm trying to create two different figures based on the same previous one.
The previous one (fig
) contains a line, common for both figures, from where two new figures are created (fig1
and fig2
), each of them with different data (df1
and df2
, respectively).
This is what I'd like to obtain:
I have tried using fig.add_subplot
function, but an error is constantly raised:
ValueError: The Subplot must have been created in the present figure
I have created an example to show what I mean. The Value Error is shown when it's executed:
import pandas as pd
import matplotlib.pyplot as plt
# Data for the two different figures
df1 = pd.DataFrame({'x':np.random.rand(80), 'y':np.random.rand(80)})
df2 = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10)})
fig, ax = plt.subplots()
# Line creation for both figures
ax.plot(([1,2]))
# Try of creating the two different figures from the previous one:
fig1 = fig.add_subplot(df1.plot(x = 'x', y = 'y', kind = 'scatter'))
fig2 = fig.add_subplot(df2.plot(x = 'x', y = 'y', kind = 'scatter'))
In this example would be very easy to create the line inside of each figure, but that could not be done in the case that I'm working at.
Upvotes: 1
Views: 2842
Reputation: 7676
You can pass ax
as an argument for df.plot
import pandas as pd
import matplotlib.pyplot as plt
# Data for the two different figures
df1 = pd.DataFrame({'x':np.random.rand(80), 'y':np.random.rand(80)})
df2 = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10)})
fig, ax = plt.subplots(nrows=1,ncols=2)
# Line creation for both figures
ax[0].plot(([1,2]))
ax[1].plot(([1,2]))
# Try of creating the two different figures from the previous one:
df1.plot(x = 'x', y = 'y', kind = 'scatter', c='violet',ax=ax[0])
df2.plot(x = 'x', y = 'y', kind = 'scatter', c='navy',ax=ax[1])
ax[0].set_title('one')
ax[1].set_title('two')
the output figure is
UPDATE
The ax
is an array of Axes
objects. Different Axes
objects are independent, they can have different labels, legends, ticks, etc. If you really need two figures for two plots
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Data for the two different figures
df1 = pd.DataFrame({'x':np.random.rand(80), 'y':np.random.rand(80)})
df2 = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10)})
# fig 1
fig_0 = plt.figure(0)
ax_0 = fig_0.add_subplot(111)
ax_0.plot(([1,2]))
df1.plot(x = 'x', y = 'y', kind = 'scatter', c='violet',ax=ax_0)
ax_0.set_title('one')
fig_1 = plt.figure(1)
ax_1 = fig_1.add_subplot(111)
ax_1.plot(([1,2]))
df2.plot(x = 'x', y = 'y', kind = 'scatter', c='navy',ax=ax_1)
ax_1.set_title('two')
fig_0.savefig('one.png')
fig_1.savefig('two.png')
You will see from the two saved files, the two plots are in two different figures.
Upvotes: 2