2

I can get a graph drawn using the plot function. But I would like to highlight some "special" points by having the projections drawn on the axes and putting text on both the point and the axes.

Something like this: enter image description here

I tried with this:

import matplotlib.pyplot as plt

[...]
plt.plot(X, Y, label='data')  # draw curve, X and Y are arrays
plt.plot(Xp, Yp, c, duration), marker='o') # draw point @(Xp, Yp), Xp and Yp are scalars
plt.vlines(Xp, min(Y), Yp, linestyles='dashed')
plt.hlines(Yp, min(X), Xp, linestyles='dashed')
plt.grid(True)
plt.show()

but what I get is not satisfactory:

enter image description here

What is the right way to get what I want?
I've also considered annotate, but it doesn't seem to do what I need. Correct me if I'm wrong.

mastupristi
  • 1,240
  • 1
  • 13
  • 29

3 Answers3

3

You can use annotate with a blended transformation:

import matplotlib.pyplot as plt

plt.plot([1,2], [2,4], label='data')
plt.plot([1.7], [3.4], marker='o')
plt.grid(True)

x,y = 1.7, 3.4
arrowprops={'arrowstyle': '-', 'ls':'--'}
plt.annotate(str(x), xy=(x,y), xytext=(x, 0), 
             textcoords=plt.gca().get_xaxis_transform(),
             arrowprops=arrowprops,
             va='top', ha='center')
plt.annotate(str(y), xy=(x,y), xytext=(0, y), 
             textcoords=plt.gca().get_yaxis_transform(),
             arrowprops=arrowprops,
             va='center', ha='right')

enter image description here

It's not perfect as the you'll still may want to manually adjust the axis coordinates (e.g. -0.05 instead of 0) to set the labels a bit off the axes.

Stef
  • 28,728
  • 2
  • 24
  • 52
1

You need to play around with xlim and ylim a bit.

For me this worked:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == "__main__":
    X = np.linspace(-.5, 3, 100)
    Y = 15000 - 10 * (X - 2.2) ** 2
    Xp = X[-10]
    Yp = Y[-10]

    plt.plot(X, Y, label='data')
    plt.plot(Xp, Yp, marker='o')
    plt.vlines(Xp, min(Y), Yp, linestyles='dashed')
    plt.hlines(Yp, min(X), Xp, linestyles='dashed')
    plt.grid(True)
    plt.xlim(min(X), None)
    plt.ylim(min(Y), None)
    plt.show()

enter image description here

Lydia van Dyke
  • 2,466
  • 3
  • 13
  • 25
0

Something like that maybe is the answer that you are searching for. https://stackoverflow.com/a/14434334/14920085

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123] #text that you want to print at the points
fig, ax = plt.subplots()
ax.scatter(z, y)
ax.set_ylabel('y')
ax.set_xlabel('x')
for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))