【问题标题】:Polar chart with limit and anomalous points带有极限点和异常点的极坐标图
【发布时间】:2018-05-08 16:15:34
【问题描述】:

考虑以下数据框,

d = {'Score': [0.25, 0.52, 0.26, 0.22, 0.31, 2.45, 3.68, 41.3, 87, 91], 
     'Thr1': 16.5,
     'Thr2': 45.5,  
     'Anomaly':[0, 0, 0, 0, 0, 0, 0, 1, 1, 1]}

df = pd.DataFrame(data = d)

我要做的是绘制一个极坐标图,用虚线表示阈值,或用多条虚线表示多个阈值,并用不同的颜色表示异常。到目前为止,我得到的是,

r = df['Score']
theta = df.index.values
fig = plt.figure()
ax = fig.add_subplot(111, projection = 'polar')
c = ax.scatter(theta, r)

我无法获得阈值并更改异常点的颜色。有什么想法吗?

【问题讨论】:

标签: python python-3.x pandas matplotlib


【解决方案1】:

您需要在阈值级别绘制一条虚线,以指示阈值在哪里。 (一条线将在极坐标图上显示为一个圆圈)。

然后您需要根据它们是否低于、介于或高于阈值来分离要绘制在散点图上的值,并相应地为点着色。

import matplotlib
matplotlib.use('TkAgg')

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


dataset = {'Score': [0.25, 0.52, 0.26, 0.22, 0.31, 2.45, 3.68, 41.3, 87, 91], 
           'Thr1': 16.5,
           'Thr2': 45.5,  
           'Anomaly':[0, 0, 0, 0, 0, 0, 0, 1, 1, 1]}

df = pd.DataFrame(data=dataset)

scores = df['Score']
theta, thr_1, thr_2 = df.index.values, dataset['Thr1'], dataset['Thr2']

fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')

# assigns a color to each point based on their relative value to the thresholds
colors = ['b' if val < thr_1 else 'y' if val < thr_2 else 'r' for val in scores]
point_cloud = ax.scatter(theta, scores, color=colors, marker='o')

# Drawing the threshold dash lines (with alpha value 1/2)
theta_xs, thr_y1, thr_y2 = np.linspace(0, 2*np.pi, 20), [thr_1] * 20, [thr_2] * 20
thr_line_1 = ax.plot(theta_xs, thr_y1, color='blue', linestyle='--', alpha=0.5)
thr_line_2 = ax.plot(theta_xs, thr_y2, color='green', linestyle='--', alpha=0.5)

plt.show()

【讨论】:

  • 谢谢。非常易读的版本。虚线阈值线也可以是不同的颜色吗?
  • 不客气;是的,您可以通过更改相关的 kwargs 来设置每个阈值的颜色(以及 alpha 值,或线条样式、粗细等)。我在代码中添加了注释。
【解决方案2】:

好吧,我不确定这是否是您想要的,因为我从未使用过您的数据集的 Anomaly 部分,而只是从 Score 数组中获取颜色信息

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as c
d = {'Score': [0.25, 0.52, 0.26, 0.22, 0.31, 2.45, 3.68, 41.3, 87, 91],
     'Thr1': 16.5,
     'Thr2': 45.5,
     'Anomaly': [0, 0, 0, 0, 0, 0, 0, 1, 1, 1]}

df = pd.DataFrame(data = d)

r = df['Score']
theta = df.index.values
fig = plt.figure()
ax = fig.add_subplot(111, projection = 'polar')

#Add thresholds
ax.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*d['Thr1'], c='g', ls='--')
ax.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*d['Thr2'], c='r', ls='--')

#Add colors
colors = ['g' if v < d['Thr1'] else 'y' if v < d['Thr2'] else "r" for v in r]
sc = ax.scatter(theta, r, c=colors)

plt.show()

【讨论】:

  • 非常感谢。它不必使用 df 的异常列。一旦您捕获大于阈值的值并重新着色它们,这就是我所需要的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
相关资源
最近更新 更多