scatter plot wiht connected vertical lines from y=ˇ0 in python

To create a scatter plot with connected vertical lines from y=0 in Python using Matplotlib, you can follow these steps:

  1. Import the necessary libraries:
main.py
import matplotlib.pyplot as plt
import numpy as np
51 chars
3 lines
  1. Generate random data for x and y coordinates:
main.py
np.random.seed(0)    # for reproducible results
x = np.random.rand(10)
y = np.random.rand(10)
94 chars
4 lines
  1. Create a scatter plot using plt.scatter:
main.py
plt.scatter(x, y, color='blue', label='Data')
46 chars
2 lines
  1. Iterate over the data points and draw vertical lines using plt.vlines:
main.py
for i in range(len(x)):
    plt.vlines(x[i], 0, y[i], color='gray', linestyle='dashed')
88 chars
3 lines
  1. Set y-axis limit to start from 0 using plt.ylim:
main.py
plt.ylim(0, None)
18 chars
2 lines
  1. Add gridlines using plt.grid for better visualization (optional):
main.py
plt.grid(True, linestyle='--', linewidth=0.5)
46 chars
2 lines
  1. Add labels and legends:
main.py
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
45 chars
4 lines
  1. Show the plot:
main.py
plt.show()
11 chars
2 lines

Here is the complete code:

main.py
import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)    # for reproducible results
x = np.random.rand(10)
y = np.random.rand(10)

plt.scatter(x, y, color='blue', label='Data')

for i in range(len(x)):
    plt.vlines(x[i], 0, y[i], color='gray', linestyle='dashed')

plt.ylim(0, None)

plt.grid(True, linestyle='--', linewidth=0.5)

plt.xlabel('x')
plt.ylabel('y')
plt.legend()

plt.show()
406 chars
22 lines

This will create a scatter plot with connected vertical lines from y=0 using a random set of data points. Feel free to modify the code according to your specific requirements.

gistlibby LogSnag