在Pandas身上标注Xaxis标签

2024-09-27 23:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

上面的图片就是我想要的。注意红色注释Big event happend,其中有一个指向X轴标签2017-12-08的箭头。在

目前我的代码:

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

if __name__ == '__main__':

    df = pd.DataFrame({
        'experiment': [1, 2, 3],
        'control': [2, 3, 4],
        'date': ['2017-12-08', '2017-12-09', '2017-12-10'],
    })

    df['date'] = pd.to_datetime(df['date'])

    df.plot(x='date', y=['experiment', 'control'])

    plt.show()

到目前为止我的成绩

enter image description here


Tags: importeventdfdatematplotlibas图片plt
1条回答
网友
1楼 · 发布于 2024-09-27 23:27:51

以下是使用^{}的一种方法(请参阅文档中的大量示意性配置选项):

ax = df.plot(x='date', y=['experiment', 'control'])
ax.annotate('Big event happened', 
            xy=(df.date[1], 1), xytext=(3, 15),
            textcoords='offset points', 
            arrowprops=dict(facecolor='red', shrink=0.05))

plot

Matplotlib足够聪明,可以处理x坐标的日期时间格式。您还可以使用date2num将日期值转换为其内部数字表示形式,如this answer所示。在

相关问题 更多 >

    热门问题