How to add outliers as separate colored markers to a line plot(如何将离群值作为单独的彩色标记添加到折线图中)
本文介绍了如何将离群值作为单独的彩色标记添加到折线图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
val time
5.6 2021-11-18 03:00:00
2.034 2021-11-18 05:00:00
1.171 2021-11-18 07:00:00
3.023 2021-11-18 09:00:00
4.202 2021-11-18 16:00:00
1.202 2021-11-18 17:00:00
5.202 2021-11-18 18:00:00
7.202 2021-11-18 19:00:00
2.202 2021-11-18 20:00:00
12.202 2021-11-18 21:00:00
1.202 2021-11-18 21:00:00
上面是我的数据框,我想绘制它(x=时间,y=值),并将值绘制为红色WHERE(val>;5)。
plt.plot(ab['time'], ab['value'], '-gD', markevery=marks, label='line with select markers')
其中mark[7.202,12.202]
是我手动创建的列表。但这并不管用。
error -: markevery is iterable but not a valid numpy fancy index
Line plot with different markers if condition is true python 3我在这里找到了一个,但如果点很多,这会很耗时
推荐答案
- 最简单的解决方案是使用Boolean indexing为大于5的值创建单独的数据框,然后使用
pandas.DataFrame.plot
将其绘制为散点图
- x轴的格式自动设置为
%M-%d %H
。当有更多数据时,格式将更改,还有其他答案讨论如何设置 pandas 日期时间轴的格式。
import pandas as pd
import matplotlib.pyplot as plt
# sample data
data = {'val': [5.6, 2.034, 1.171, 3.023, 4.202, 1.202, 5.202, 7.202, 2.202, 12.202, 1.202], 'time': ['2021-11-18 03:00:00', '2021-11-18 05:00:00', '2021-11-18 07:00:00', '2021-11-18 09:00:00', '2021-11-18 16:00:00', '2021-11-18 17:00:00', '2021-11-18 18:00:00', '2021-11-18 19:00:00', '2021-11-18 20:00:00', '2021-11-18 21:00:00', '2021-11-18 21:00:00']}
df = pd.DataFrame(data)
# convert the time column to a datetime dtype
df.time = pd.to_datetime(df.time)
# get the values greater than 5
masked = df[df.val.gt(5)]
# plot the line plot
ax = df.plot(x='time', marker='o', figsize=(15, 5), zorder=0)
# plot those greater than 5
masked.plot(kind='scatter', x='time', y='val', color='red', ax=ax, s=30, label='outliers')
这篇关于如何将离群值作为单独的彩色标记添加到折线图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何将离群值作为单独的彩色标记添加到折线图中


基础教程推荐
猜你喜欢
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01