[英]Create a parametric arrow in matplotlib returning and annotating the difference between two points in the plot
我的重点是根据输入数据自动绘制箭头及其长度。
我被困在如何创建一个自动获取 x1,y1,y2 坐标并返回的 function 上:
像这样的东西:
def draw_arrow(x,y,yy,shift=0):
tform = blended_transform_factory(ax.transAxes, ax.transAxes)
x_end=x.iloc[-1]+shift
y_end=y.iloc[-1]
yy_end=yy.iloc[-1]
half=(y_end+yy_end)/2
diff=str(abs(y_end-yy_end))
annotation=plt.annotate('', xy = (x_end, y_end), xycoords = tform, \
xytext = (x_end, yy_end), textcoords = tform, fontsize = 7, \
color = '#303030', arrowprops=dict(edgecolor='black', arrowstyle = '<->', shrinkA = 0, shrinkB = 0),)
text=plt.text(x_end*1.10,half,str())
return annotation,text
这是我为这个问题创建的代码:
retention_dict= {'Month':[0,1,2,3,4,5,6],
'Ret_30':[1000, 1300, 1390, 1417, 1425, 1428, 1428],
'Ret_40':[1000, 1400, 1560, 1624, 1650, 1660, 1664],
'Ret_50':[1000, 1500, 1750, 1875, 1938, 1969, 1984]}
ret_df=pd.DataFrame(retention_dict)
def draw_arrow(x,y,yy,shift=0):
tform = blended_transform_factory(ax.transAxes, ax.transAxes)
x_end=x.iloc[-1]+shift
y_end=y.iloc[-1]
yy_end=yy.iloc[-1]
half=(y_end+yy_end)/2
diff=str(abs(y_end-yy_end))
annotation=plt.annotate('', xy = (x_end, y_end), xycoords = tform, \
xytext = (x_end, yy_end), textcoords = tform, fontsize = 7, \
color = '#303030', arrowprops=dict(edgecolor='black', arrowstyle = '<->', shrinkA = 0, shrinkB = 0),)
text=plt.text(x_end*1.10,half,str())
return annotation,text
fig, ax =plt.subplots(facecolor='lightgray')
formatter = ticker.FormatStrFormatter('%1.0f')
ax.yaxis.set_major_formatter(formatter)
plt.grid(True)
figure_title = "Retention Rate tells us \n % of customers that did not shop again \n after the first puchase"
figure_expl = "Hp. Every 10$ we invest in marketing(FB ads/Google) \n we acquire one new customer"
ax=plt.plot(ret_df['Month'], ret_df['Ret_30'],
ret_df['Month'], ret_df['Ret_40'],
ret_df['Month'], ret_df['Ret_50']
)
plt.text(3,2050, figure_title,
horizontalalignment='center',
fontsize=10,
)
plt.text(3,970, figure_expl,
horizontalalignment='center',
fontsize=10,
)
#draw_arrow(ret_df['Month'],ret_df['Ret_30'],ret_df['Ret_40'])
plt.title('Retention Rate ', pad=50)
plt.xlabel('Months')
plt.ylabel('Customers')
plt.show()
我也看过:
这个问题“ 在 matplotlib 中向参数图中添加箭头”
这个问题“ 是否可以将 matplotlib 注释锚定到 x 轴上的数据坐标,但锚定到 y 轴上的相对位置? ”
本章文档使用复坐标和注解
但我还是有问题
我可能简化了太多,但是为什么需要转换? 我解释您的问题的方式是这样的,您只需要指定要绘制的箭头的索引(在本例中为which_month )
def draw_arrow(x,y,yy, shift=0, which_month=-2):
x_end=x.iloc[which_month]+shift
y_end=y.iloc[which_month]
yy_end=yy.iloc[which_month]
half=(y_end+yy_end)/2
diff=str(abs(y_end-yy_end))
annotation=plt.annotate('', xy = (x_end, y_end),
xycoords = 'data', \
xytext = (x_end, yy_end), textcoords = 'data', fontsize = 7, \
color = '#303030', arrowprops=dict(edgecolor='black', arrowstyle = '<->', shrinkA = 0, shrinkB = 0),)
text=plt.text(x_end*1.01,half,diff)
return annotation,text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.