得利於語言的簡單明瞭、豐富的數據結構、豐富的類和模塊,Python如今成了數據科學中的香餑餑,成了matlab、R語言之外又一強大的數據分析工具。拋開其他方面的、今天蟲蟲帶大家一起來探索Python在數據可視化方面的應用。我們以最基本的幾種圖標為實例來介紹Python matplotlib的強大的作圖能力。
1.折線圖
在繪製折線圖時,如果你的數據很小,圖表的線條有點折,當你數據集比較大時候,比如超過100個點,則會呈現相對平滑的曲線。
在這裡,我們使用三個plt.plot繪製了,不同斜率(1,2和3)的三條線。
import numpy as np
import matplotlib.pyplot as plt
cc= np.linspace(0,2,100)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.plot(cc,cc,label='linear')
plt.plot(cc,cc**2,label='兩倍')
plt.plot(cc,cc**3,label='三倍')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("折線圖")
plt.legend()
plt.show()
cc = np.linspace(0,2,100)
plt.plot(cc,cc,label ='linear')
plt.plot(cc,cc ** 2,label ='quadratic')
plt.plot(cc,cc ** 3,label ='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
結果顯示,如下:
注意為了顯示中文,我們plt.rcParams屬性設置了中文字體,不然不能正確顯示中文title的。
2.散點圖
散點圖和折線圖的原理差不多;如果使用直線連接散點圖中的點,得到的就是折線圖。所以你只需要設置線型來繪製散點圖。
注意:次例中我們也畫了三行。不同的地方時,只使用了一個plt.plot。
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
plt.plot(x, x, 'r--', x, x**2, 'bs', x, x**3, 'g^')
plt.show()
圖表顯示結果為:
3.直方圖
直方圖也是一種常用的簡單圖表,本例中我們在同一張圖片中繪製兩個概率直方圖。
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
mu1, sigma1 = 100, 15
mu2, sigma2 = 80, 15
x1 = mu1 + sigma1 * np.random.randn(10000)
x2 = mu2 + sigma2 * np.random.randn(10000)
n1, bins1, patches1 = plt.hist(x1, 50, density=True, facecolor='g', alpha=1)
n2, bins2, patches2 = plt.hist(x2, 50, density=True, facecolor='r', alpha=0.2)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.xlabel('智商')
plt.ylabel('置信度')
plt.title('IQ直方圖')
plt.text(110, .025, r'$\mu=100,\ \sigma=15$')
plt.text(50, .025, r'$\mu=80,\ \sigma=15$')
# 設置座標範圍
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
顯示效果為:
4.條形圖
我們要介紹的第四種,圖表類型是條形圖,我們這兒引入稍微比較複雜的條形圖。
4.1平行條形圖
此例中,我們引入三組(a,b,c)5個隨機數(0~1),並用條形圖打印出來,做比較
import numpy as np
import matplotlib.pyplot as plt
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
total_width, n = 0.8, 3
width = total_width / n
# redraw the coordinates of x
x = x - (total_width - width) / 2
# here is the offset
plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()
顯示效果為:
4.2堆積條形圖
數據同上,不過條形plot的時候,用的相互的值大小差異(水平方向),而不是條柱平行對比。
import numpy as np
import matplotlib.pyplot as plt
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
plt.bar(x, a, width=0.5, label='a',fc='r')
plt.bar(x, b, bottom=a, width=0.5, label='b', fc='g')
plt.bar(x, c, bottom=a+b, width=0.5, label='c', fc='b')
plt.ylim(0, 2.5)
plt.legend()
plt.grid(True)
plt.show()
顯示效果為:
5.餅圖
餅圖是對比數量比例的最佳顯示方式。
5.1一般餅圖
ABCD四個數據,我們以餅圖方式顯示器大小對比。
import matplotlib.pyplot as plt
labels = 'A', 'B', 'C', 'D'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)
plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
plt.axis('equal')
plt.show()
顯示效果為:
5.2嵌套餅圖
import numpy as np
import matplotlib.pyplot as plt
size = 0.3
vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
cmap = plt.get_cmap("tab20c")
outer_colors = cmap(np.arange(3)*4)
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
print(vals.sum(axis=1))
# [92. 77. 39.]
plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
wedgeprops=dict(width=size, edgecolor='w'))
print(vals.flatten())
# [60. 32. 37. 40. 29. 10.]
plt.pie(vals.flatten(), radius=1-size, colors=inner_colors,
wedgeprops=dict(width=size, edgecolor='w'))
# equal makes it a perfect circle
plt.axis('equal')
plt.show()
顯示效果為:
5.3極軸餅圖
極軸餅圖是一種非常酷的圖表,讓我們看他的源碼:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(19680801)
N = 10
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
ax = plt.subplot(111, projection='polar')
bars = ax.bar(theta, radii, width=width, bottom=0.0)
for r, bar in zip(radii, bars):
bar.set_facecolor(plt.cm.viridis(r / 10.))
bar.set_alpha(0.5)
plt.show()
顯示效果為:
6.3D圖表
3D圖表也是能我們展示出超想象力的視覺效果的圖表。
6.1三維散點圖
首先來看看三維的散點圖,源碼:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data = np.random.randint(0, 255, size=[40, 40, 40])
x, y, z = data[0], data[1], data[2]
ax = plt.subplot(111, projection='3d')
ax.scatter(x[:10], y[:10], z[:10], c='y')
ax.scatter(x[10:20], y[10:20], z[10:20], c='r')
ax.scatter(x[30:40], y[30:40], z[30:40], c='g')
ax.set_zlabel('Z')
ax.set_ylabel('Y')
ax.set_xlabel('X')
plt.show()
顯示效果為:
6.2 3D平面圖
我們要用到mpl_toolkits.mplot3d這個3D模塊包,安裝這個包後,繪製一個超酷的3D圖只需兩行代碼:
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
顯示效果為:
怎麼樣,效果很酷把,好今天蟲蟲就給大家介紹到這裡,如果你有任何問題,或者需要本文提到的源碼包,請關注蟲蟲,給蟲蟲留言。
閱讀更多 蟲蟲安全 的文章