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



我正在运行的用于获取此图(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_boundlower_bound时,这些点将以不同的颜色标记为'x'。最后,我要让一个点超过阈值1个标准偏差,将其标记为橙色,如果一个点超过2个或更多标准偏差,则将其标记为红色。我在列df_shader下的数据框StanDev中具有所有标准差。每当我尝试运行if块的某些变体时,都会遇到变量错误和名称错误

最佳答案

您可以使用布尔掩码选择满足某些条件的点,
并绘制它们:

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)


结果:

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

关于python - 根据跨越边界的数量,突出显示颜色超过或低于阈值的matplotlib点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45208226/

10-12 17:33