我正在尝试根据相同的前一个创建两个不同的图。
上一个(fig
)包含两个图形共有的一行,从中创建两个新图形(fig1
和fig2
),每个图形都有不同的数据(df1
和df2
)。
这是我想要获得的:
我尝试使用fig.add_subplot
函数,但是不断出现错误:ValueError: The Subplot must have been created in the present figure
我创建了一个例子来说明我的意思。执行时会显示“值错误”:
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.
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句