我遇到了thispost,它详细介绍了如何将ggplot
对象合并到matplotlib
网格中。这个过程包括首先生成一个ggplot
对象,获取当前图形,然后使用基于状态的API在现有图形上构建更多的子图。你知道吗
我想使用面向对象的API来复制它,以便使它更具可扩展性。你知道吗
import ggplot as gp
import matplotlib.pyplot as plt
g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds) + gp.geom_point() + gp.ylab('price') + gp.xlab('carat')
g.make()
f1 = plt.gcf()
g = gp.ggplot(gp.aes(x='price', y='carat'), data=gp.diamonds) + gp.geom_point() + gp.ylab('carat') + gp.xlab('price')
g.make()
f2 = plt.gcf()
(fig, axes) = plt.subplots(1,2, figsize=(20,10))
axes[0] = f1.axes[0]
axes[0].set_title('Price vs. Carat')
axes[1] = f2.axes[0]
axes[1].set_title('Carat vs. Price')
fig.show()
我写这篇文章的动机不仅仅局限于ggplot
库,因为理想情况下,我也希望使用几个不同库(如seaborn
或bokeh
)的图形来创建网格。使用面向对象的API从图形中提取轴并将其添加到matplotlib
图形网格的最佳方法是什么?你知道吗
编辑:正如@ImportanceOfBeingErnest所建议的,我尝试了另一种方法:
import ggplot as gp
import matplotlib.pyplot as plt
g = gp.ggplot(gp.aes(x='carat', y='price'), data=gp.diamonds) + gp.geom_point() + gp.ylab('price')+ gp.xlab('carat')
g.make()
f1 = plt.gcf()
g = gp.ggplot(gp.aes(x='price', y='carat'), data=gp.diamonds) + gp.geom_point() + gp.ylab('carat')+ gp.xlab('price')
g.make()
f2 = plt.gcf()
plt.show()
def add_axis(fig, ggFig, pos):
ggAxis = ggFig.axes[0]
ggAxis.remove()
ggAxis.figure = fig
fig.axes.append(ggAxis)
fig.add_axes(ggAxis)
dummy = fig.axes[pos]
ggAxis.set_position(dummy.get_position())
dummy.remove()
plt.close(ggFig)
(fig, axes) = plt.subplots(1,2, figsize=(20,10))
add_axis(fig, f2, 1)
add_axis(fig, f1, 0)
fig.show()
奇怪的是,如果用pos=1调用add_axis,然后用pos=0调用add_axis,则这种方法是有效的,但反过来不行。为什么会这样?你知道吗
axes[0] = f1.axes[0]
只是意味着axes
数组的第一个元素现在是另一个图形的轴。这并不意味着这个轴有任何事情要做,甚至在图fig
中显示出来。你知道吗linked question的答案显示了如何继续:使用ggplot创建一个图形,并向它添加更多的轴,还可能更改现有轴的位置。 这也可以通过seaborn实现。你知道吗
也可以尝试从现有地物移动(而不是复制)轴。如How to plot multiple Seaborn Jointplot in Subplot所示。你知道吗
在Can I create AxesSubplot objects, then add them to a Figure instance?中详细介绍了一般方法。你知道吗
但是请注意,这些都是黑客攻击。一般不建议移动轴,现有解决方案有一些警告。 相反,可以要求这些库的维护人员最终提供选项,用他们的工具绘制现有的matplotlib图形。你知道吗
除了其他评论,这里还有另一个黑客:保存图像到一个图像,然后使用plt.imshow公司()
它不漂亮,但很管用。你知道吗
相关问题 更多 >
编程相关推荐