将来自不同来源的多个轴添加到同一图形中

问题描述 投票:0回答:2

我正在使用Python / matplotlib创建一个图形,其中它具有三个子图,每个子图均从不同的“源”或类方法返回。

例如,我有一个名为'plot_spectra.py'的脚本,其中包含带有方法Spectra()Plot()类。

因此,按照下面的代码调用Spectra('filename.ext')。Plot()将返回一个元组:

# create the plot
fig, ax = plt.subplots()
ax.contour(xx, yy, plane, levels=cl, cmap=cmap)
ax.set_xlim(ppm_1h_0, ppm_1h_1)
ax.set_ylim(ppm_13c_0, ppm_13c_1)

# return the contour plot
return fig, ax

据我了解,“图”是matplotlib中的“窗口”,而“ ax”是一个单独的图。然后,我想说的是,在同一图中绘制这些“ ax”对象中的三个,但是我一直在努力这样做,因为我一直在空着一个窗口,而且我认为我误解了每个对象的实际含义。

呼叫:

hnca, hnca_ax = Spectra('data/HNCA.ucsf', type='sparky').Plot(plane_ppm=resi.N(), vline=resi.H())
plt.subplot(2,2,1)
plt.subplot(hnca_ax)

eucplot, barplot = PlotEucXYIntensity(scores, x='H', y='N')

plt.subplot(2,2,3)
plt.subplot(eucplot)

plt.subplot(2,2,4)
plt.subplot(barplot)

plt.show()

最终,我要获取的是一个看起来像这样的单个窗口:

enter image description here

每个图从不同的函数或类方法返回的位置。

我需要从函数中返回什么'对象'?以及如何将这三个对象合并为一个图形?

python matplotlib
2个回答
0
投票

一种方法是:

f = plt.figure()
gs = f.add_gridspec(2,2)
ax = f.add_subplot(gs[0,:])

将'2,2'视为添加2行x 2列。在第三行'gs [0 ,:]'告诉您在第0行的所有列上添加一个图表。这将在顶部顶部创建图表。请注意,索引以0开头,而不以1开头。

要添加'eucplot',您将不得不在第1行和第0列调用另一个斧头:

ax2 = f.add_subplot(gs[1,0])

最后,'barplot'将进入第1行第1列的另一把斧头上。

ax3 = f.add_subplot(gs[1,1])

请参阅此处以获取更多参考:Customizing Figure Layouts Using GridSpec and Other Functions


0
投票

我建议使用这种方法,在此函数中指定要绘制的斧头:

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

def Spectra(data, ax):
  ax.plot(data)

def PlotIntensity(data, ax):
  ax.hist(data)

def SeabornScatter(data, ax):
  sns.scatterplot(data, data, ax = ax)

spectrum = np.random.random((1000,))

plt.figure()

ax1 = plt.subplot(1,3,1)
Spectra(spectrum, ax1)

ax2 = plt.subplot(1,3,2)
SeabornScatter(spectrum, ax2)

ax3 = plt.subplot(1,3,3)
PlotIntensity(spectrum, ax3)

plt.tight_layout()
plt.show()

您可以以非常不同的方式为子图指定网格,并且您可能还想看看gridspec模块。

© www.soinside.com 2019 - 2024. All rights reserved.