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

2024-05-23 18:14:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python/matplotlib创建了一个图,其中有三个子图,每个子图都从不同的“源”或类方法返回

例如,我有一个名为“plot_spectra.py”的脚本,它包含方法为Plot()Spectra()

因此,调用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

据我所知,“figure”是matplotlib中的“window”,而“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

其中,每个绘图都是从不同的函数或类方法返回的

我需要从函数返回什么“对象”?如何将这三个对象合并到一个图形中?


Tags: the对象方法plotmatplotlibfigpltax
2条回答

我建议采用这种方法,即指定要在函数中绘制的ax:

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()

您可以用非常不同的方式为子地块指定网格,并且您可能还希望查看^{}模块

一种方法是:

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列调用不同的ax:

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

最后,“条形图”将进入第1行第1列的另一个ax:

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

请参阅此处的此网站以获取进一步参考:Customizing Figure Layouts Using GridSpec and Other Functions

相关问题 更多 >