Skip to content Skip to sidebar Skip to footer

Pyplot: Adding Point Projections On Axis

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

Solution 1:

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.


Solution 2:

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

Solution 3:

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


Post a Comment for "Pyplot: Adding Point Projections On Axis"