Skip to main content
 首页 » 编程设计

python之Matplotlib:在连接到寄生虫轴的数据上绘制数据标签

2025年05月04日10lyj

这是“如何绘制数据标签”问题的变体,我在 SO 上看到过一些地方。但是,我从未见过它在寄生虫轴上完成。

基本上,我想要连接到寄生虫(右)垂直轴的时间序列(绿色)的每个点上方的数据标签。

这是我目前拥有的:

from mpl_toolkits.axes_grid1 import host_subplot 
import matplotlib.pyplot as plt 
 
times=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] 
plotorder=[239, 133, 94, 42, 31, 27, 49, 99, 172, 292, 397, 439, 450, 391, 429, 374, 382, None, None, None, None, None, None, None] 
lastyearorders=[119, 78, 49, 29, 14, 12, 30, 46, 108, 154, 194, 224, 181, 199, 213, 186, 167, 152, 135, 115, 99, 106, 97, 90] 
difference=[100.8, 70.5, 91.8, 44.8, 121.4, 125.0, 63.3, 115.2, 59.3, 89.6, 104.6, 96.0, 148.6, 96.5, 101.4, 101.1, 128.7, None, None, None, None, None, None, None] 
ordersMax=max(plotorder+lastyearorders) 
growthMax=max(difference) 
 
host = host_subplot(111) 
 
par = host.twinx() 
host.set_xlabel("Hour") 
host.set_ylabel("Orders") 
par.set_ylabel("% Growth") 
host.set_xlim(0,24) 
host.set_ylim(0,ordersMax*1.1) 
par.set_ylim(0,growthMax*2) 
p1, = host.plot(times, plotorder, linewidth=2, marker='o', color='r', label="Today's Orders") 
p1, = host.plot(times, lastyearorders, linewidth=2, color='b', label="LY Orders") 
p2, = par.plot(times, difference, marker='s', color='green', label="% Growth") 
leg = plt.legend() 
plt.show() 

我试过同时使用 par.plot_text(times[1], difference[1], difference[1]) 和 par.annotate(),但是都抛出了错误,说 AttributeError: 'AxesParasite' object has no attribute 'plot_text'

这是我目前拥有的:

我想要这样的东西(来自 Excel):

请您参考如下方法:

for (x,y) in zip(times, difference): 
    if y: 
         par.annotate("{0}%".format(y), xy=(x, y+10)) 

这似乎对我有用,你尝试注释什么?