matplotlib 从X轴到Y轴的箭头(反之亦然)[重复]

0vvn1miw  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(131)

此问题已在此处有答案

Simple and two head arrows(4个答案)
Plot a horizontal line on a given plot(7个回答)
How to draw vertical lines on a given plot(6个答案)
How to specify arrow coordinates(1个答案)
Arrow properties in matplotlib annotate(1个回答)
上个月关门了。
我不能让我的头周围重新创建所附的图像。我看了花式箭头等,但我不能创建蓝色和红色箭头。
这是我到目前为止所拥有的:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
from scipy.stats import norm

# Generate random data from a continuous distribution (e.g., normal distribution)
data = np.random.normal(0, 1, 100)  # Mean = 0, Standard Deviation = 1

# Calculate the CDF
sorted_data = np.sort(data)
cdf = np.arange(1, len(sorted_data) + 1) / len(sorted_data)

plt.figure(figsize=(8, 6))
plt.plot(sorted_data, cdf, label='Empirical CDF')

# Generate random points on the x and y axes
random_x = np.random.choice(sorted_data, 1)[0]
random_y = np.random.uniform(0, 1, 1)[0]

# Plot arrows
arrow1 = FancyArrowPatch((random_x, 0), (random_x, random_y), color='red', arrowstyle='-|>', mutation_scale=15)
arrow2 = FancyArrowPatch((0, random_y), (random_x, random_y), color='blue', arrowstyle='-|>', mutation_scale=15)
plt.gca().add_patch(arrow1)
plt.gca().add_patch(arrow2)

plt.annotate(f'({random_x:.2f}, {random_y:.2f})', (random_x + 0.1, random_y + 0.02), color='black')

plt.title('Cumulative Distribution Function (CDF) with Arrows')
plt.xlabel('X-axis')
plt.ylabel('Cumulative Probability')
plt.legend()
plt.grid(True)
plt.show()

vuv7lop3

vuv7lop31#

从图像中可以看出,x和y的随机值并不相互对应,但应该分别用于不同颜色的箭头。对于每种颜色,箭头在碰到曲线时都会转向一个轴。因此,我将每个箭头分成2部分,一个指向曲线(arrowi1),一个指向远离曲线(arrowi2)的点。此外,您需要plt.xlim()才能到达图的最左边部分。

# generate random index in order to access x/y corresponding to the curve
idx_x = np.random.choice(range(len(sorted_data)), 1)[0]
random_x = sorted_data[idx_x]

idx_y = np.random.choice(range(len(sorted_data)), 1)[0]
random_y = cdf[idx_y]

# Plot arrows
arrow11 = FancyArrowPatch((random_x, 0), (random_x, cdf[idx_x]), color='red', arrowstyle='-', mutation_scale=15)
arrow12 = FancyArrowPatch((random_x, cdf[idx_x]), (plt.xlim()[0], cdf[idx_x]), color='red', arrowstyle='-|>', mutation_scale=15)

arrow21 = FancyArrowPatch((plt.xlim()[0], random_y), (sorted_data[idx_y], random_y), color='blue', arrowstyle='-', mutation_scale=15)
arrow22 = FancyArrowPatch((sorted_data[idx_y], random_y), (sorted_data[idx_y], 0), color='blue', arrowstyle='-|>', mutation_scale=15)

plt.gca().add_patch(arrow11)
plt.gca().add_patch(arrow12)
plt.gca().add_patch(arrow21)
plt.gca().add_patch(arrow22)

相关问题