温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Merge matplotlib subplots with shared x-axis
matplotlib python subplot

python - 将Matplotlib子图与共享的X轴合并

发布于 2020-05-06 11:56:03

我有两个图,其中两个都有相同的x轴,但y轴的缩放比例不同。

带有规则轴的图是带有趋势线的数据,该趋势线描述了衰减,而y半对数标度则描述了拟合的准确性。

fig1 = plt.figure(figsize=(15,6))
ax1 = fig1.add_subplot(111)

# Plot of the decay model 
ax1.plot(FreqTime1,DecayCount1, '.', color='mediumaquamarine')

# Plot of the optimized fit
ax1.plot(x1, y1M, '-k', label='Fitting Function: $f(t) = %.3f e^{%.3f\t} \
         %+.3f$' % (aR1,kR1,bR1))

ax1.set_xlabel('Time (sec)')
ax1.set_ylabel('Count')
ax1.set_title('Run 1 of Cesium-137 Decay')

# Allows me to change scales
# ax1.set_yscale('log')
ax1.legend(bbox_to_anchor=(1.0, 1.0), prop={'size':15}, fancybox=True, shadow=True)

在此处输入图片说明 在此处输入图片说明

现在,我想找出将两者紧密结合在一起的方法,例如此链接http://matplotlib.org/examples/pylab_examples/subplots_demo.html提供的示例

特别是这个

在此处输入图片说明

在查看示例代码时,我对如何植入3件事有些困惑:

1)不同比例缩放轴

2)对于指数衰减图,图形尺寸保持相同,但具有线图的y尺寸较小,x尺寸相同。

例如:

在此处输入图片说明

3)使功能标签仅出现在衰减图中。

非常感激任何的帮助。

查看更多

提问者
iron2man
被浏览
15
Serenity 2016-06-10 10:05

查看其中的代码和注释:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import gridspec

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig = plt.figure()
# set height ratios for sublots
gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1]) 

# the fisrt subplot
ax0 = plt.subplot(gs[0])
# log scale for axis Y of the first subplot
ax0.set_yscale("log")
line0, = ax0.plot(x, y, color='r')

#the second subplot
# shared axis X
ax1 = plt.subplot(gs[1], sharex = ax0)
line1, = ax1.plot(x, y, color='b', linestyle='--')
plt.setp(ax0.get_xticklabels(), visible=False)
# remove last tick label for the second subplot
yticks = ax1.yaxis.get_major_ticks()
yticks[-1].label1.set_visible(False)

# put lened on first subplot
ax0.legend((line0, line1), ('red line', 'blue line'), loc='lower left')

# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)
plt.show()

在此处输入图片说明