如何在Matplotlib多组散点之间添加从value1指向value2的箭头
修改方案
你只需将原代码中绘制水平灰色线段的plt.hlines()逻辑替换为逐行绘制水平箭头的代码即可实现需求,以下是完整可运行的修改后代码:
import numpy as np import pandas as pd import matplotlib.pyplot as plt # 生成测试数据集 value1=np.random.uniform(size=20) value2=value1+np.random.uniform(size=20)/4 df = pd.DataFrame({'group':list(map(chr, range(65, 85))), 'value1':value1 , 'value2':value2 }) # 按value1数值排序 ordered_df = df.sort_values(by='value1') my_range=range(1,len(df.index)+1) # 替换原hlines代码,绘制从value1(蓝色点)指向value2(绿色点)的水平箭头 for y, x1, x2 in zip(my_range, ordered_df['value1'], ordered_df['value2']): plt.arrow(x=x1, y=y, dx=x2-x1, dy=0, head_width=0.2, head_length=0.02, length_includes_head=True, color='grey', alpha=0.4) plt.scatter(ordered_df['value1'], my_range, color='skyblue', alpha=1, label='value1') plt.scatter(ordered_df['value2'], my_range, color='green', alpha=0.4 , label='value2') plt.legend() # 添加轴标签和标题 plt.yticks(my_range, ordered_df['group']) plt.title("Comparison of the value 1 and the value 2", loc='left') plt.xlabel('Value of the variables') plt.ylabel('Group') plt.show()
参数调整说明
如果箭头显示效果不符合预期,可以调整两个参数适配:
head_width:控制箭头头部的垂直高度,默认0.2可根据y轴刻度间距调整head_length:控制箭头头部的水平长度,默认0.02可根据x轴数值范围调整
原有代码生成的参考图表:
内容的提问来源于stack exchange,提问作者Henri
相关产品推荐
相关产品推荐

