Alena
Alena

Reputation: 15

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') 

Upvotes: 0

Views: 110

Answers (3)

Pierre D
Pierre D

Reputation: 26201

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()

Upvotes: 3

jared
jared

Reputation: 8981

To draw a line at a specific y value and that extends from one x value to another in the data coordinates, use plt.hlines (the vertical equivalent is plt.vlines). This can be done for each individual line:

plt.hlines(y=1, xmin=0, xmax=5, colors="red", linestyles="--")
plt.hlines(y=0.83193, xmin=0, xmax=4, colors="red", linestyles="--")

Or for a list of lines:

y = [0.47178, 0.16308, 0.03078]
xmin = 0
xmax = [3, 2, 1]
plt.hlines(y=y, xmin=xmin, xmax=xmax, colors="red", linestyles="--")

Upvotes: 3

Suraj Shourie
Suraj Shourie

Reputation: 2605

There is an easy way to add a horizontal line using plt.axhline. But this line will be unbounded.

If you want to fully replicate your image you want a line segment which you can add by plt.plot.

I've added code for both below, so that you can choose whichever is more appropriate for your usecase.

plt.axhline(0.47, c='black', ls = "--" ) # Unbounded horizontal Line
plt.plot([0,5], [1,1], c='black', ls = "--") # Line segment

enter image description here

Upvotes: 0

Related Questions