【问题标题】:Adding specific dots to a series plot in Python在 Python 中将特定点添加到系列图中
【发布时间】:2020-11-27 23:30:57
【问题描述】:

我有一个时间序列图,我想在特定时间索引处添加一个红点。下面是一个示例代码:

    dt_index = pd.to_datetime(['2020-01-01','2020-02-01','2020-03-01','2020-04-01','2020-05-01'])
    series = pd.Series([1.1,2.2,3.3,4.5,6.7], index = dt_index)
    dots_to_add = pd.to_datetime(['2020-01-01','2020-04-01'])
    series.plot()

使用dots_to_add 作为索引,如何在行中添加一个红点?

【问题讨论】:

  • 你试过 plt.axis(...) 吗?
  • 难道 plt.axis() 不只是限制 x 和 y 轴吗?我希望在 (x = '2020-01-01', y = 1.1) 和 (x = '2020-04-01', y = 4.5) 上添加一个红点。抱歉,我的问题可能不太清楚。
  • 不是熊猫人,但你可以做ax = series.plot() 和后来的ax.scatter(…., color='red') 用省略号我已经指出了一些泛泛的东西,在 Numpy 中会是 ax.scatter(some_abscissae, all_ordinates[some_abscissae], color='red') - 注意这不是一个答案'cs 我不知道足够多的 Pandas 来给出完整的答案

标签: python matplotlib time-series data-visualization


【解决方案1】:

图中的一个点称为marker

import pandas as pd
import matplotlib.pyplot as plt

dt_index = pd.to_datetime(['2020-01-01','2020-02-01','2020-03-01','2020-04-01','2020-05-01'])
series = pd.Series([1.1,2.2,3.3,4.5,6.7], index = dt_index)
dots_to_add = pd.to_datetime(['2020-01-01','2020-04-01'])
series.plot(marker='o')

plt.show()

我没有找到使标记颜色和绘图颜色不同的参数。我认为没有,因为标记是情节的一部分,它们应该具有相同的样式。

但我认为您可以改为绘制散点图:

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

dt_index = pd.to_datetime(['2020-01-01','2020-02-01','2020-03-01','2020-04-01','2020-05-01'])
series = pd.Series([1.1,2.2,3.3,4.5,6.7], index = dt_index)
dots_to_add = pd.to_datetime(['2020-01-01','2020-04-01'])

series.plot()
plt.scatter(series.index, series, color='r')

plt.show()

如果您只想添加以dots_to_add 作为索引的点,您可以使用for 循环,每个循环plt.scatter() 一个点。

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

dt_index = pd.to_datetime(['2020-01-01','2020-02-01','2020-03-01','2020-04-01','2020-05-01'])
series = pd.Series([1.1,2.2,3.3,4.5,6.7], index = dt_index)
dots_to_add = pd.to_datetime(['2020-01-01','2020-04-01'])

series.plot()

for dot in dots_to_add:
    plt.scatter(dot, series[dot], color='r')

plt.show()

【讨论】:

    猜你喜欢
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 2018-10-06
    • 2018-04-17
    • 1970-01-01
    相关资源
    最近更新 更多