Python數據可視化系列-01-快速繪圖


快速繪圖

數據圖繪制

matplotlib的字庫pyplot提供了快速繪制2D圖標的API接口。

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 1000)
y = np.sin(x)
z = np.cos(x**2)
plt.figure(figsize=(8, 4))
plt.plot(x, y, label="$sin(x)$", color="red", linewidth=2)
plt.plot(x, z, "b--", label="$cos(x^2)$")
plt.xlabel("Time(s)")
plt.ylabel("Volt")
plt.title("PyPlot First Example")
plt.ylim(-1.2, 1.2)
plt.legend()
plt.show()

數據圖屬性配置

Figure對象
Figure對象,此對象在調用plt.figure函數時返回,通過plt.gcf函數獲取當前的繪圖對象
語法plt.gcf()

axes屬性
Figure對象有一個axes屬性,其值為AxesSubplot對象的列表,每個AxesSubplot對象代表圖表
中的一個子圖,前面所繪制的圖表只包含一個子圖,當前子圖也可以通過plt.gca獲得。

設置和得到屬性方法
set_*
plt.setp函數配置多個Line2D對象的顏色和線寬屬性
get_*
plt.getp函數獲取對象的屬性值

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1)

# plot函數返回一個 matplotlib.lines.Line2D 對象的列表
line, = plt.plot(x, x*x) # plot返回一個列表,通過line,獲取其第一個元素
line.set_antialiased(False) # 調用Line2D對象的set_*方法設置屬性值
line.get_linewidth()

# 同時繪制sin和cos兩條曲線,lines是一個有兩個Line2D對象的列表
lines = plt.plot(x, np.sin(x), x, np.cos(x))
# 調用setp函數同時配置多個Line2D對象的多個屬性值
plt.setp(lines, color="r", linewidth=2.0)
plt.getp(lines[0], "color") # 返回color屬性
plt.getp(lines[1]) # 輸出全部屬性

f = plt.gcf() # get current Figure 對象
plt.getp(f) # 得到當前figure對象的全部屬性
plt.getp(f, "axes") # 得到當前axes屬性, Figure對象有一個axes屬性
# [<matplotlib.axes.AxesSubplot object at 0x05CDD170>]
plt.gca() # 得到當前axes屬性, Figure對象有一個axes屬性
# <matplotlib.axes.AxesSubplot object at 0x05CDD170>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM