簡體   English   中英

合並具有共享 x 軸的 matplotlib 子圖

[英]Merge matplotlib subplots with shared x-axis

我有兩個圖表,它們都具有相同的 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) 保持函數的標簽只出現在衰減圖中。

非常感激任何的幫助。

看看里面的代碼和注釋:

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

在此處輸入圖片說明

這是我的解決方案:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, subplot_kw=dict(frameon=False)) # frameon=False removes frames

plt.subplots_adjust(hspace=.0)
ax1.grid()
ax2.grid()

ax1.plot(x, y, color='r')
ax2.plot(x, y, color='b', linestyle='--')

在此處輸入圖片說明

一種選擇是seaborn.FacetGrid但這需要 Seaborn 和 Pandas 庫。

以下是一些修改,用於展示在繪制 Pandas 數據框時代碼如何添加組合圖例。 ax=ax0可用於在給定的ax上繪圖,並且ax0.get_legend_handles_labels()獲取圖例的信息。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

dates = pd.date_range('20210101', periods=100, freq='D')
df0 = pd.DataFrame({'x': np.random.normal(0.1, 1, 100).cumsum(),
                    'y': np.random.normal(0.3, 1, 100).cumsum()}, index=dates)
df1 = pd.DataFrame({'z': np.random.normal(0.2, 1, 100).cumsum()}, index=dates)

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [2, 1], 'hspace': 0})

df0.plot(ax=ax0, color=['dodgerblue', 'crimson'], legend=False)
df1.plot(ax=ax1, color='limegreen', legend=False)

# put legend on first subplot
handles0, labels0 = ax0.get_legend_handles_labels()
handles1, labels1 = ax1.get_legend_handles_labels()
ax0.legend(handles=handles0 + handles1, labels=labels0 + labels1)

# remove last tick label for the second subplot
yticks = ax1.get_yticklabels()
yticks[-1].set_visible(False)

plt.tight_layout()
plt.show()

使用熊貓繪圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM