Matplotlib,使用 plt.text() 和 Pandas 时间序列数据设置绘图内文本 [英] Matplotlib, settng in-plot text with plt.text() with pandas time series data

查看:193
本文介绍了Matplotlib,使用 plt.text() 和 Pandas 时间序列数据设置绘图内文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Matplotlib 允许使用 matplotlib.axes.Axes.text() 在绘图中设置文本.

Matplotlib allows one to set text within the plot inself with matplotlib.axes.Axes.text().

我正在绘制 Pandas 系列数据,所以 x 轴是日期.

I am plotting Pandas Series data, so the x-axis are dates.

Datetime
2014-11-08    345
2014-11-09    678 
2014-11-10    987
2014-11-11    258
Freq: W-SUN, dtype: int64

如果我想添加文本添加位置(x,y) = (2014-11-08, 345),我该怎么做?2014-11-08 实际上不是 x 轴上的 x 值.我怎样才能找到这个位置?

If I wanted to add text add location (x,y) = (2014-11-08, 345), how could I do this? 2014-11-08 is not actually the x value on the x-axis. How can I find this location?

推荐答案

有几个选项.您可以使用来自 Python 标准库的 datetime 或 pandas 的 的 Series 对象索引、datedatetime 对象的值Timestamp 对象,用于设置时间序列图上标签的 x 轴位置.

There are several options. You can either use the values from the Series objects' index, date or datetime objects from the Python standard library's datetime or pandas' Timestamp object to set the x-axis location of a label on a time-series plot.

import pandas as pd
from pandas import Timestamp
import datetime as dt
import matplotlib.pyplot as plt

s = pd.Series({Timestamp('2014-11-08 00:00:00'): 345,
    Timestamp('2014-11-09 00:00:00'): 678,
    Timestamp('2014-11-10 00:00:00'): 987,
    Timestamp('2014-11-11 00:00:00'): 258})

fig = plt.figure()
ax = fig.gca()
s.plot(ax=ax)

i = 0
ax.text(s.index[i], s.iloc[i], "Hello")
ax.text(dt.date(2014, 11, 9), 500, "World")
ax.text(Timestamp("2014-11-10"), 777, "!!!")

plt.show()

这篇关于Matplotlib,使用 plt.text() 和 Pandas 时间序列数据设置绘图内文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆