pythonmatplotlibyaxisarrows

Is there a way to specify y-axis marks on a matplotlib.pyplot plot?


I need to plot a distribution function using python.

enter image description here

I have drawn some arrows (red on black below), but I don’t know how to create those horizontal dashed lines representing the needed values of a function (what is expected is shown above).

This is my current code:

import matplotlib.pyplot as plt 

plt.arrow(x=1 , y= 0.00243 , dx= -0.9 , dy= 0 , width= .01, facecolor = 'red', edgecolor = 'none') 
plt.arrow (x=2 , y= 0.03078 , dx= -0.99999 , dy= 0 , width= .01, facecolor = 'red', edgecolor = 'none') 
plt.arrow (x=3 , y= 0.16308 , dx= -0.99999 , dy= 0 , width= .01, facecolor = 'red', edgecolor = 'none') 
plt.arrow(x=4 , y= 0.47178 , dx= -0.99999 , dy= 0 , width= .01, facecolor = 'red', edgecolor = 'none') 
plt.arrow(x=5 , y= 0.83193 , dx= -0.99999 , dy= 0 , width= .01, facecolor = 'red', edgecolor = 'none') 
plt.arrow(x=6 , y= 1 , dx= -0.99999 , dy= 0 , width= .01, facecolor = 'red', edgecolor = 'none') 

Solution

  • Here is a plot with:

    1. the y ticks set as per your example figure, and labels showing 5 decimals,
    2. dashed lines from the y axis to the arrows,
    3. arrow heads with a better (subjective) aspect ratio,
    4. arrows with the head included in the overall length (no need to fudge),
    5. plot margins adjusted so that the dashed lines go all the way to the y axis.
    import numpy as np
    
    y = np.array([0.00243, 0.03078, 0.16308, 0.47178, 0.83193, 1])
    x = np.arange(len(y))
    
    fig, ax = plt.subplots(figsize=(6, 4))
    ax.hlines(y=y, xmin=0, xmax=x, color='r', linestyles='--')
    for xi, yi in zip(x, y):
        ax.arrow(xi + 1, yi, -1, 0, color='r', width=.01,
                 head_length=.15, length_includes_head=True)
    ax.margins(x=0)
    ax.set_yticks(y, [f'{yi:.5f}' for yi in y])
    plt.show()