Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Matplotlib พล็อตฟังก์ชัน Sine ด้วย Python

Matplotlib: แพ็กเกจ Python ยอดนิยมสำหรับ Data Visualization ช่วยเข้าใจข้อมูลและสื่อสารข้อมูลเชิงปริมาณ สร้างกราฟ 2D ด้วย Object-oriented API รองรับ IPython, Jupyter, Spyder เขียนด้วย Python บน NumPy

การติดตั้งและ Dependencies

pip install matplotlib
Python (>= 3.4), NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil

ตัวอย่าง: พล็อต Sine Wave

import matplotlib.pyplot as plt
import numpy as np

data = np.arange(0.0, 4.0, 0.1)
y = 2 + np.sin(2 * np.pi * data)

fig, ax = plt.subplots()
ax.plot(data, y)
ax.set(xlabel='x-axis data', ylabel='y-axis data', title='A simple plot')
ax.grid()
plt.show()

ผลลัพธ์

วิธีใช้ Matplotlib พล็อตฟังก์ชัน Sine ด้วย Python

คำอธิบาย

  • นำเข้าแพ็กเกจและตั้งอเลียส
  • สร้างข้อมูลด้วย NumPy (arange)
  • คำนวณค่า Y = 2 + sin(2πx)
  • สร้าง Figure และ Axes ด้วย subplots()
  • พล็อตด้วย plot()
  • ตั้งค่า Label และ Title ด้วย ax.set()
  • แสดง Grid ด้วย ax.grid()
  • แสดงผลด้วย show()