Skip to main content
 首页 » 编程设计

python之根据越过边界的数量,以颜色突出显示超过或低于阈值的 matplotlib 点

2025年05月04日14yxwkf

我有一个看起来像这样的图表:

我正在运行以获取此图(8 个图的序列之一)的代码如下:

date_list =  list(df_testing_set['date'].unique()) 
 
random_date_list = list(np.random.choice(date_list,8)) 
 
df_new = df_testing_set[df_testing_set['date'].isin(random_date_list)] 
 
for date1 in random_date_list: 
df_new = df_testing_set[df_testing_set['date'] == date1] 
title = date1 
 
if df_new.iloc[0]['day'] in ['Saturday', 'Sunday']: 
    df_shader = df_result_weekend.copy() 
    title += " - Weekend" 
else: 
    df_shader = df_result_weekday.copy() 
    title += " - Weekday" 
 
y = df_new[row_index].tolist() 
x = range(0, len(y)) 
x_axis = buckets 
y_axis = df_shader.loc[df_shader.index.isin([row_index]) & df_shader['Bucket'].between(1, 144), data_field].tolist() 
del y_axis[-1] 
 
 
plt.title(title) 
plt.xlabel("Time of Day (10m Intervals)") 
plt.ylabel(data_field + " values for " + row_index) 
 
standevs = df_shader.loc[df_shader.index.isin([row_index]) & df_shader['Bucket'].between(1, 144), 'StanDev'].tolist() 
del standevs[-1] 
lower_bound = np.array(y_axis) - np.array(standevs) 
upper_bound = np.array(y_axis) + np.array(standevs) 
 
plt.fill_between(x_axis, lower_bound, upper_bound, facecolor='lightblue') 
 
#highlighting anomalies 
#   if (y > upper_bound | y < lower_bound): 
#       plt.plot(x,y, 'rx') 
#   else: 
#       plt.plot(x, y) 
 
 
 
plt.plot(x,y) 
plt.show() 
 
del df_shader, title, date1, df_new 

我正在尝试创建一个条件(如注释的 if 语句),以便当绘制的坐标高于阈值 upper_bound 或低于 lower_bound 时,这些点是标有不同颜色的“x”。我最终想要这样,如果一个点超过阈值 1 个标准差,它将标记为橙色,如果超过 2 个或更多标准差,它将标记为红色。我在 StanDev 列下的数据框 df_shader 中拥有所有标准偏差。每当我尝试运行 if block 的某些变体时,我都会遇到变量错误和名称错误

请您参考如下方法:

您可以使用 bool 掩码来选择满足特定条件的点, 并绘制它们:

import matplotlib.pyplot as plt 
import numpy as np 
 
std = 0.1 
N = 100 
 
x = np.linspace(0, 1, N) 
expected_y = np.sin(2 * np.pi * x) 
y = expected_y + np.random.normal(0, std, N) 
 
dist = np.abs(y - expected_y) / std 
 
mask1 = (1 < dist) & (dist <= 2) 
mask2 = dist > 2 
 
plt.fill_between(x, expected_y - 0.1, expected_y + 0.1, alpha=0.1) 
plt.fill_between(x, expected_y - 0.2, expected_y + 0.2, alpha=0.1) 
 
plt.plot(x, y) 
plt.plot(x[mask1], y[mask1], 'x') 
plt.plot(x[mask2], y[mask2], 'x') 
 
 
plt.tight_layout() 
plt.savefig('mp_points.png', dpi=300) 

结果: