Matplotlib 在放大标签编码类时对 axvline 进行抗锯齿处理

问题描述 投票:0回答:1

我有这个代码:

# Display parameter
Xt = X_test[0, 0:1024]
a = 1
lw = 1

# Get mask of every classes
bl_pred = yp == 0
p_pred = yp == 1
qrs_pred = yp == 2
t_pred = yp == 3

# Plotting
for i in range(len(Xt)):
  if bl_pred[i]:
    plt.axvline(x=i, color='grey', linestyle='-', alpha=a, linewidth=lw)
  elif p_pred[i]:
    plt.axvline(x=i, color='orange', linestyle='-', alpha=a, linewidth=lw)
  elif qrs_pred[i]:
    plt.axvline(x=i, color='green', linestyle='-', alpha=a, linewidth=lw)
  elif t_pred[i]:
    plt.axvline(x=i, color='purple', linestyle='-', alpha=a, linewidth=lw)
plt.plot(Xt, color='blue')

plt.show()

无问题返回图像: enter image description here

但是当我将数据范围放大到较小的范围时,如下所示:

# Display parameter
Xt = X_test[0, 0:256] # smaller scope
a = 1
lw = 1

它返回别名图像: enter image description here

这可以通过增加线宽来解决:

# Display parameter
Xt = X_test[0, 0:256]
a = 1
lw = 1.4 # increasing line width manually

enter image description here

但是,我不想手动调整线宽。如何让它自动调整?也许可以根据当前显示的每个节点的差异来计算?但我不知道其语法。

python matplotlib visualization
1个回答
0
投票

谢谢@JohanC

它可以使用

axvspan

import matplotlib.pyplot as plt
import numpy as np

# Sample data

# Display parameter
Xt = X_test[0, :256]
a = 0.5

# Get mask of every class
bl_pred = yp == 0
p_pred = yp == 1
qrs_pred = yp == 2
t_pred = yp == 3

# Plotting
fig, ax = plt.subplots()
prev_class = None
start_idx = 0

for i in range(len(Xt)):
    current_class = None
    if bl_pred[i]:
        current_class = 'grey'
    elif p_pred[i]:
        current_class = 'orange'
    elif qrs_pred[i]:
        current_class = 'green'
    elif t_pred[i]:
        current_class = 'purple'

    if current_class != prev_class:
        if prev_class is not None:
            ax.axvspan(start_idx, i, color=prev_class, alpha=a)
        start_idx = i
        prev_class = current_class

# Fill the last region
if prev_class is not None:
    ax.axvspan(start_idx, len(Xt), color=prev_class, alpha=a)

ax.plot(Xt, color='blue')
plt.show()

返回: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.