如何使用python和matplotlib注释行尾?

问题描述 投票:10回答:2

具有这样的数据框和基本图:

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

np.random.seed(123456)
rows = 75
df = pd.DataFrame(np.random.randint(-4,5,size=(rows, 3)), columns=['A', 'B', 'C'])
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df = df.cumsum()

df.plot()

enter image description here

注释直线上最后一点的最佳方法是什么,以便获得以下结果?

enter image description here

python matplotlib
2个回答
12
投票

为了注释点,请使用ax.annotate()。在这种情况下,有必要指定要单独注释的坐标。即y坐标是线的最后一点的数据坐标(您可以从line.get_ydata()[-1]中获得),而x坐标与数据无关,并且应该是轴的右侧(即,轴中的1坐标)。然后,您可能还需要稍微偏移文本,以使其与轴不重叠。

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

rows = 75
df = pd.DataFrame(np.random.randint(-4,5,size=(rows, 3)), columns=['A', 'B', 'C'])
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist 
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df = df.cumsum()

ax = df.plot()

for line, name in zip(ax.lines, df.columns):
    y = line.get_ydata()[-1]
    ax.annotate(name, xy=(1,y), xytext=(6,0), color=line.get_color(), 
                xycoords = ax.get_yaxis_transform(), textcoords="offset points",
                size=14, va="center")

plt.show()

enter image description here


5
投票

方法1

这里是一种方法,或者至少是一种方法,您可以使用plt.annotate方法以任何想要的方式适应美学上的适合:

[编辑]:如果您要使用像第一个这样的方法,在ImportanceOfBeingErnest的答案中概述的方法要比我提出的要好。

df.plot()

for col in df.columns:
    plt.annotate(col,xy=(plt.xticks()[0][-1]+0.7, df[col].iloc[-1]))

plt.show()

Plot

对于xy自变量,即文本的x和y坐标,我选择了plt.xticks()中的最后一个x坐标,并添加了0.7,使其位于x轴之外,但是您可以使如果您认为合适,则可以更靠近或更远。

方法2

您也可以只使用右y轴,并用3行标记它。例如:

fig, ax = plt.subplots()
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)

plt.show()

这将为您提供以下情节:

plot2 annotated y

© www.soinside.com 2019 - 2024. All rights reserved.