Home > Software design >  Show integer points in coordinate system
Show integer points in coordinate system

Time:12-01

Say I have a simple pyplot:

import matplotlib.pyplot as plt
plt.plot([-1, -4.5, 3.14, 1])
plt.show()

Which generates the following:

plot

How do I show all Integer points in the graph, so it looks like:

enter image description here

CodePudding user response:

You can use plt.xlim/plt.ylim to get the limits and numpy.meshgrid to generate the points, then plt.scatter to plot them:

import matplotlib.pyplot as plt

plt.plot([-1, -4.5, 3.14, 1])


x0,x1 = plt.xlim()
y0,y1 = plt.ylim()

import numpy as np

X,Y = np.meshgrid(np.arange(round(x0), round(x1) 1),
                  np.arange(round(y0), round(y1) 1))

plt.scatter(X,Y)

output:

enter image description here

CodePudding user response:

Here's a very primitive method.

import matplotlib.pyplot as plt
import numpy as np

plt.plot([-1, -4.5, 3.14, 1])

# Get interger points of x and y within the axes
xlim = np.round(plt.xlim(), 0)
list_x = np.arange(xlim[0], xlim[1] 1)
ylim = np.round(plt.ylim(), 0)
list_y = np.arange(ylim[0], ylim[1] 1)

# Get mesh grids for the points
mesh_x, mesh_y = np.meshgrid(list_x, list_y)

# Make grids to vectors
list_x = mesh_x.flatten()
list_y = mesh_y.flatten()

# Plot points
plt.plot(list_x, list_y, ls="none", marker=".")

plt.show()

CodePudding user response:

import matplotlib.pyplot as plt
l = [-1, -4.5, 3.14, 1]
plt.plot(l)
integers = [[x, y] for x in range(len(l)) for y in range(math.floor(min(l)), math.ceil(max(l)))] 
x_int_points, y_int_points = list(zip(*integers))
plt.scatter(x=x_int_points, y=y_int_points) 
plt.show()

Generalized:

def plot_with_grid(l):
    integers = [[x, y] for x in range(len(l)) \
                       for y in range(math.floor(min(l)), 
                                      math.ceil(max(l)))] 
    x_int_points, y_int_points = list(zip(*integers))
    plt.plot(l)
    plt.scatter(x=x_int_points, y=y_int_points) 
    plt.show()
  • Related