programing

Python 플롯에 그리드를 그리려면 어떻게 해야 하나요?

luckcodes 2022. 10. 28. 22:14

Python 플롯에 그리드를 그리려면 어떻게 해야 하나요?

Python에서 pylab을 사용하여 플롯을 작성하는 코드 작성을 마쳤기 때문에 10x10의 그리드를 산란도에 중첩하고 싶습니다.그걸 어떻게 하는 거죠?

현재 코드는 다음과 같습니다.

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.show()

출력은 다음과 같습니다.

그리드 미포함

제가 원하는 것은 다음과 같은 출력입니다.

그리드 포함

편집: Andrey Sobolev의 답변을 바탕으로 예제를 추가했습니다.

사용하고 싶다pyplot.grid:

x = numpy.arange(0, 1, 0.05)
y = numpy.power(x, 2)

fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(0, 1, 0.1))
ax.set_yticks(numpy.arange(0, 1., 0.1))
plt.scatter(x, y)
plt.grid()
plt.show()

ax.xaxis.grid그리고.ax.yaxis.grid는 그리드선 속성을 제어할 수 있습니다.

여기에 이미지 설명을 입력하십시오.

모든 눈금에 격자선을 표시하려면

plt.grid(True)

예를 들어 다음과 같습니다.

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.scatter(x, y)
plt.grid(True)

plt.show()

여기에 이미지 설명 입력


또한 스타일(예: 점선 대신 실선)을 사용자 지정하고 다음을 추가할 수 있습니다.

plt.rc('grid', linestyle="-", color='black')

예를 들어 다음과 같습니다.

import matplotlib.pyplot as plt

points = [
    (0, 10),
    (10, 20),
    (20, 40),
    (60, 100),
]

x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))

plt.rc('grid', linestyle="-", color='black')
plt.scatter(x, y)
plt.grid(True)

plt.show()

여기에 이미지 설명 입력

rcParams를 사용하면 다음과 같이 그리드를 쉽게 표시할 수 있습니다.

plt.rcParams['axes.facecolor'] = 'white'
plt.rcParams['axes.edgecolor'] = 'white'
plt.rcParams['axes.grid'] = True
plt.rcParams['grid.alpha'] = 1
plt.rcParams['grid.color'] = "#cccccc"

이러한 파라미터를 변경해도 그리드가 표시되지 않으면

plt.grid(True)

부르기 전에

plt.show()

다음은 Python 2에서 Gtk3에 matplotlib 그리드를 추가하는 간단한 예입니다(Python 3에서는 동작하지 않습니다).

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

win = Gtk.Window()
win.connect("delete-event", Gtk.main_quit)
win.set_title("Embedding in GTK3")

f = Figure(figsize=(1, 1), dpi=100)
ax = f.add_subplot(111)
ax.grid()

canvas = FigureCanvas(f)
canvas.set_size_request(400, 400)
win.add(canvas)

win.show_all()
Gtk.main()

여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/8209568/how-do-i-draw-a-grid-onto-a-plot-in-python