假設我有一個簡單的 pyplot:
import matplotlib.pyplot as plt
plt.plot([-1, -4.5, 3.14, 1])
plt.show()
這會生成以下內容:

我如何在圖中顯示所有整數點,所以它看起來像:

uj5u.com熱心網友回復:
您可以使用plt.xlim/plt.ylim獲取限制并numpy.meshgrid生成點,然后plt.scatter繪制它們:
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)
輸出:

uj5u.com熱心網友回復:
這是一個非常原始的方法。
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()
uj5u.com熱心網友回復:
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()
概括:
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371220.html
標籤:Python matplotlib
上一篇:matplotlib.axes.Axes.set_xticks拋出“set_ticks()需要2個位置引數,但給出了3個”
