簡體   English   中英

子圖,如何設置 xlabel 和 xlim,但刪除軸

[英]subplots, how to set the xlabel and xlim, but removing axis

我想 plot EEG 數據並得到這個結果:

參考圖

但我被困在如何顯示x軸 label 及其xlim

在閱讀了其他使用set_visible(False)的問題后,我無法解決我的問題。

我編寫代碼是為了可重現:

sfreq = 256
raw_data = np.random.rand(14, 1000 * sfreq)

duration = 10 # duration of the signal
start = 200 * sfreq
final = start + int(sfreq * duration)  

channels = list(np.arange(1, len(channels) + 1 ))

fig, ax = plt.subplots(len(channels), 1, sharex=True, figsize=(10, 10))
for idx, node in enumerate(channels):
    data = raw_data[idx, start:final]
    times = np.arange(1, data.size + 1) / sfreq
    ax[idx].plot(times, data, lw=1., ls='-', c='k')
    
    ax[idx].axis('off') # to remove bounding subplot    
    ax[idx].set_yticks([]) # to remove values from y axis   
    ax[idx].text(-1, 0, node, fontsize=12) # write text
    

# plt.axis(True)
# plt.axes().get_xaxis().set_visible(True)
# plt.xlim([200, 220])
plt.xlabel('Time (seconds)', fontsize=12)
plt.tight_layout()
plt.show()

這是我的結果:

當前結果

但我想要這樣:

期望的結果

以下是 plot 的一些可能更改:

  • 通過使用zip而不是for循環中的索引,使代碼更 python
  • 更改“脊椎”(圍繞子圖的線)的可見性,而不是使用axis('off')
  • 刪除填充(邊距)
  • 使用軸轉換為 position y 軸的文本
  • ...
import matplotlib.pyplot as plt
import numpy as np

sfreq = 256
raw_data = np.random.rand(14, 1000 * sfreq)

duration = 10  # duration of the signal
start = 200 * sfreq
final = start + int(sfreq * duration)

channels = np.arange(len(raw_data)) + 1

fig, axs = plt.subplots(len(channels), 1, sharex=True, figsize=(10, 10))
for ax, node, data in zip(axs, channels, raw_data):
    data = data[start:final]
    times = np.arange(1, data.size + 1) / sfreq
    ax.plot(times, data, lw=1., ls='-', c='k')

    ax.set_yticks([])  # remove y ticks
    for sp in ax.spines:
        ax.spines[sp].set_visible(False)  # hide the 4 lines surrounding the subplot
    ax.text(-0.01, 0.5, node, fontsize=12, ha='right', va='center', transform=ax.transAxes)  # write text
    ax.margins(x=0) # avoid the empty space left and right
    if ax != axs[-1]:
        # ax.tick_params(axis='x', length=0)  # hide the tick marks
        ax.tick_params(bottom=False)  # no tick marks at the bottom

axs[-1].set_xlabel('Time (seconds)', fontsize=12, labelpad=-10) # use negative padding to get closer to the xaxis
axs[-1].set_xticks([0, duration])
axs[-1].set_xticklabels([start // sfreq, final // sfreq])
axs[-1].spines['bottom'].set_bounds([0, duration])  # only draw the spine between the two ticks
axs[-1].spines['bottom'].set_visible(True)
axs[-1].spines['bottom'].set_linewidth(2)
plt.tight_layout()
plt.show()

修改的子圖

暫無
暫無

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

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