python - 合并具有共享 x 轴的 matplotlib 子图

标签 python matplotlib subplot

我有两个图表,它们都具有相同的 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)

enter image description here enter image description here

现在,我正在尝试将两者紧密地实现在一起,就像此链接提供的示例一样 http://matplotlib.org/examples/pylab_examples/subplots_demo.html

特别是这个

enter image description here

在查看示例代码时,我对如何植入 3 个东西感到有点困惑:

1) 以不同方式缩放轴

2) 保持指数衰减图的图形大小相同,但折线图具有较小的 y 大小和相同的 x 大小。

例如:

enter image description here

3) 保持函数的标签只出现在衰减图中。

如有任何帮助,我们将不胜感激。

最佳答案

看里面的代码和注释:

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 subplots
gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1]) 

# the first 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 legend 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()

enter image description here

关于python - 合并具有共享 x 轴的 matplotlib 子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737538/

相关文章:

python - 移动补丁而不是删除它

python - python 中的正则表达式

python - For 循环在达到条件之前结束

python - 在划分两列的同时绘制三组的多个条形图

python-3.x - 在 Bokeh python 中创建雷达图的步骤是什么?

python - 当catplot图是子图的一部分时,如何修改它的 "ylabel"属性?

python - 如何在matplotlib中的子图下方添加图例?

python - 使用子图时如何使用 matplotlib.pyplot.xticks 或类似的?

python - Django Rest Framework中如何根据一些请求参数限制序列化器相关字段的查询集

python - 处理 couchdb 通知的外部进程导致崩溃