1. 程式人生 > 其它 >python畫統計圖(一)

python畫統計圖(一)

python畫統計圖

目錄

python有一個畫圖的庫matplotlib,非常方便我們日常使用或者寫論文做插圖等等。我們不需要考慮樣式的問題,輸入資料就可以輕輕鬆鬆把圖畫出來。你用Excel、matlab等工具,我也沒意見。

matplotlib: Visualization with Python

Matplotlib 是一個綜合性的庫,用於在 Python 中建立靜態、動畫和互動式視覺化。Matplotlib 使簡單的事情變得容易,使困難的事情成為可能。基於matplotlib的基礎開發的繪圖介面還有seaborn、HoloViews、ggplot,以及一個投影和對映工具包(Cartopy)。

常用頁面:

API Overview

Axes物件方法參考連結

入門

安裝

# 第一種
python -m pip install -U pip
python -m pip install -U matplotlib
# 第二種
conda install matplotlib
# linux
sudo apt-get install python3-matplotlib

使用

import matplotlib.pyplot as plt

Matplotlib都是在Figure這個概念上面進行畫圖,每個Figure都可以包含一個或多個座標

fig, ax = plt.subplots()  # Create a figure containing a single axes.
ax = plt.gca()	# Get the current axes.
fig = plt.gcf() # Get the current figure.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])  # Plot some data on the axes.

圖的組成部分

Figure組成:主要刻度、次要刻度、座標軸、座標軸標籤、刻度標籤、標記、網格、圖例等等

Figure

整個圖片Figure,包括了子類Axes。(很重要的一點是不需要過多考慮這個類Figure,因為它是實際進行繪圖以獲取繪圖的物件,但作為使用者,它或多或少對您不可見)。一個Figure可以包含任意數量的Axes,但通常至少有一個。

fig = plt.figure()	# an empty figure with no Axes
fig, ax = plt.subplots()	# a figure with a single Axes
fig, axs = plt.subplots(2, 2)	# a figure with a 2x2 grid of Axes

Axes 和 Axis

Axes看成“繪畫”區域,包含兩個或者三個Axis物件,Axis負責設定圖形限制並生成刻度(軸上的標記)和刻度標籤(標記刻度的字串)。

注:Artist物件概念最大,攬括了所有的元素。

Axes物件方法參考連結

輸入

所有的輸入都期望numpy.arraynumpy.ma.masked_array作為輸入。

風格:面向物件介面和pyplot介面

顯式:

x = np.linspace(0, 2, 100)

# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots()  # Create a figure and an axes.
ax.plot(x, x, label='linear')  # Plot some data on the axes.
ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
ax.plot(x, x**3, label='cubic')  # ... and some more.
ax.set_xlabel('x label')  # Add an x-label to the axes.
ax.set_ylabel('y label')  # Add a y-label to the axes.
ax.set_title("Simple Plot")  # Add a title to the axes.
ax.legend()  # Add a legend.

隱式:

x = np.linspace(0, 2, 100)

plt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic')  # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()

示例

方法 作用
plot() 線圖
subplot() 建立多個圖即多個子圖
imshow() 顯示影象
pcolormesh() 可以對二維陣列進行彩色表示,即使水平維度的間距不均勻。contour()函式是表示相同資料的另一種方式:
hist() 直方圖
matplotlib.path模組 新增任意路徑
mplot3d 工具包 三維繪圖
streamplot() 向量場的流線圖
bar() 條形圖
pie() 餅圖
table() 表,未知
scatter() 散點圖
plt.ion() 互動式畫圖
每天進步一點點! ©版權宣告 文章版權歸作者所有,未經允許請勿轉載。