azeez
azeez

Reputation: 497

python-3.x Draw a horizontal and vertical line for each point (scatter)

I am plotting using (matplotlib) with python-3.x and I am trying to draw a horizontal and vertical line for each point (scatter) that I am plotting based on a values that I have:

import matplotlib.pyplot as plt
x = [-0.9,  0.5  ,  -2.5,  3  , -1.5 ]
y = [2.9 ,  -1.5 ,  1   ,  1  , -2.4 ]
v = [50  ,  33   ,  21  ,  18 , 5    ]

fig = plt.figure(figsize=(10, 8))
plt.scatter(x,y, s=40 ,marker='o', c='black')
plt.grid()
plt.show()

the problem I can't really find any answer to how to draw a horizontal and vertical line for each point also how to show the values for the y-axis and x-axis for that line, as shown in the example (attached image).

Any advice would be much appreciated.

a perfect example of what I need to achieve: enter image description here

Upvotes: 0

Views: 790

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339300

You may use the minor ticks to create a grid and the respective ticklabels.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(25)

x,y = np.random.randn(2,7).round(1)

fig, ax = plt.subplots()
ax.scatter(x,y, c="crimson")


ax.set_xticks(x, minor=True)
ax.set_yticks(y, minor=True)
ax.xaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
ax.yaxis.set_minor_formatter(matplotlib.ticker.ScalarFormatter())
ax.tick_params(which="minor", labelbottom=True, labelleft=True, 
               labelcolor="crimson", pad=15)

ax.grid(which='minor', color="navy")

plt.show()

enter image description here

Upvotes: 1

Related Questions