matplotlib視覺化初體驗
阿新 • • 發佈:2018-11-27
這篇部落格主要是總結一下最近進行的matplotlib視覺化實驗,內容主要來自於官方文件的例項。
(1)首先最簡單的——圓形散點圖:
import matplotlib.pyplot as plt import numpy as np #繪製一個圓形散點圖 t = np.arange(1, 10, 0.05) x = np.sin(t) y = np.cos(t) #定義一個影象視窗 plt.figure(figsize=(8,5)) #繪製一條線 plt.plot(x, y, "r-*") #使得座標軸相等 plt.axis("equal") plt.xlabel("sin") plt.ylabel("cos") plt.title("circle") #顯示圖形 plt.show()
(2)點圖與線圖——並且用subplot()繪製多個子圖:
"""Matplotlib繪圖之點圖與線圖 並且使用subplot()繪製多個子圖 """ import numpy as np import matplotlib.pyplot as plt #生成x x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) #生成y y1 = np.cos(2*np.pi*x1) * np.exp(-x1) y2 = np.cos(2*np.pi*x2) #繪製第一個子圖 plt.subplot(2, 1, 1) plt.plot(x1, y1, 'yo-') plt.title('A tale of 2 subplots') plt.ylabel('Damped oscillation') #繪製第二個子圖 plt.subplot(2,1,2) plt.plot(x2, y2, 'r.-') plt.xlabel('time (s)') plt.ylabel('Undamped') plt.show()
(3)直方圖:
"""繪製直方圖""" import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt #樣例資料 mu = 100 sigma = 15 x = mu + sigma * np.random.randn(10000) print("x:", x.shape) #直方圖的條數 num_bins = 50 #繪製直方圖 n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) #新增一個最佳擬合曲線 y = mlab.normpdf(bins, mu, sigma)#返回關於資料的pdf值——概率密度函式 plt.plot(bins, y, 'r--') plt.xlabel('Smarts') plt.ylabel('Probability') #在圖中新增公式需要使用LaTeX的語法 plt.title('Histogram of IQ: $\mu=100$, $\sigma=15$') #調整影象的間距,防止y軸數值與label重合 plt.subplots_adjust(left=0.15) plt.show()
(4)繪製三維影象:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
n_angles = 36
n_radii = 8
# An array of radii
# Does not include radius r=0, this is to eliminate duplicate points
radii = np.linspace(0.125, 1.0, n_radii)
# An array of angles
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
# Repeat all angles for each radius
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
# Convert polar (radii, angles) coords to cartesian (x, y) coords
# (0, 0) is added here. There are no duplicate points in the (x, y) plane
x = np.append(0, (radii * np.cos(angles)).flatten())
y = np.append(0, (radii * np.sin(angles)).flatten())
# Pringle surface
z = np.sin(-x * y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2)
plt.show()
(5) 三維曲面圖以及各個軸的投影等高線:
"""三維曲面圖
三維影象and各個軸的投影等高線"""
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure(figsize=(8, 6))
ax = fig.gca(projection='3d')
#生成三維測試資料
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z',offset=-100, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x',offset=-40, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y',offset=40, cmap=cm.coolwarm)
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()
(6)條形圖:
"""條形圖"""
import numpy as np
import matplotlib.pyplot as plt
#生成資料
n_groups = 5#組數
#平均分和標準差
means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)
means_women = (25, 32,34,20,25)
std_women = (3, 5, 2, 3, 3)
#條形圖
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35#條形圖寬度
opacity = 0.4
error_config = {'ecolor': '0.3'}
#條形圖的第一類條
rects1 = plt.bar(index, means_men, bar_width,
alpha=opacity,
color='b',
yerr=std_men,
error_kw=error_config,
label='Men')
#條形圖中的第二類條
rects2 = plt.bar(index + bar_width,
means_women,
bar_width,
alpha=opacity,
color='r',
yerr=std_women,
error_kw=error_config,
label='Women')
plt.xlabel('Group')
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(index + bar_width, ('A', 'B', 'C', 'D', 'E'))
plt.legend()
#自動調整subplot的引數指定的填充區
plt.tight_layout()
plt.show()
(7)餅圖:
"""繪製餅圖"""
import matplotlib.pyplot as plt
#切片將按照順時針方向排列並繪製
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'#標註
sizes = [15,30,45,10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']#顏色
explode = (0, 0.1, 0, 0)#這裡的0.1是指第二個塊從圓裡面分割出來
plt.pie(sizes,
explode=explode,
labels=labels,
colors=colors,
autopct='%1.1f%%',
shadow=True,
startangle=90)
plt.axis('equal')
plt.show()
(8)氣泡圖:
"""氣泡圖"""
import matplotlib.pyplot as plt
import pandas as pd
#匯入資料
df_data = pd.read_csv('https://raw.github.com/pydata/pandas/master/pandas/tests/data/iris.csv')
df_data.head()
#作圖
fig, ax = plt.subplots()
#可以自行設定氣泡顏色
# colors = ['#99cc01'......]
#建立氣泡圖SepalLength為x,SepalWidth為y,設定PetalLength為氣泡大小
ax.scatter(df_data['SepalLength'],
df_data['SepalWidth'],
s=df_data['PetalLength'] * 100,
alpha=0.6)
ax.set_xlabel('SepalLength(cm)')
ax.set_ylabel('SepalWidth(cm)')
ax.set_title('PetalLength(cm) * 100')
#顯示網格
ax.grid(True)
fig.tight_layout()
plt.show()