在如今這個看顏值的時代,數(shù)據(jù)展示也要美美的。曾經(jīng),望著那一堆堆,”面無表情”的數(shù)據(jù),總感覺索然無味,暈頭轉(zhuǎn)向,好在Python有matplotlib,可以繪制美美的圖形。
生成圖形,得有數(shù)據(jù),它可用matplotlib的最佳拍檔numpy去造。
NumPy是Python中的一個運算速度非常快的一個數(shù)學(xué)庫,它非常重視數(shù)組和隨機(jī)數(shù),允許你進(jìn)行向量和矩陣計算,是科學(xué)Python成功的關(guān)鍵之一。如果你想要進(jìn)入Python中的數(shù)據(jù)科學(xué)和或機(jī)器學(xué)習(xí),你就必須學(xué)習(xí)它。
要獲得numpy和matplotlib開發(fā)庫,可通過pip3 install numpy matplotlib指令,一次性下載并自動安裝。在windows7/10下,以管理員身份打開命令行窗口。
好了,咱來點高級的。向天空畫正弦,點點星光,希望你喜歡。倘若你不喜歡,那怎么辦?--我也不知道。
import matplotlib.pyplot as plt
import numpy
import math
#圖片大小設(shè)置為:900*600
plt.rcParams['figure.figsize'] = (9.0, 6.0)
fig, ax = plt.subplots
#去掉頂部和右邊邊框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#邊框顏色
ax.spines['left'].set_color('gray')
ax.spines['bottom'].set_color('gray')
#區(qū)間是[0,4π],步長為0.1
x = numpy.arange(0, 4 * math.pi, 0.1)
y = numpy.arange(0, 4 * math.pi, 0.1)
sin = [math.sin(i) for i in x]
cos = [math.cos(i) for i in x]
plt.plot(x, sin, label='sin')
plt.plot(y, cos, label='cos')
plt.savefig('sin_cos.png')
線的顏值感覺不咋樣,換條形圖瞧瞧。如果還是覺得不好看,就找設(shè)計師畫一張吧。嘿嘿~
import numpy as np
import matplotlib.pyplot as plt
#圖片大小設(shè)置為:900*600
plt.rcParams['figure.figsize'] = (9.0, 6.0)
fig, ax = plt.subplots
#去掉頂部和右邊邊框
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#邊框顏色
ax.spines['left'].set_color('gray')
ax.spines['bottom'].set_color('gray')
size = 5
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
x = np.arange(size)
total = 1.0
n = 3
width = total / n
#重新擬定x的坐標(biāo)
x = x - (total - width) / 2
#這里使用的是偏移
plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
#存圖片在當(dāng)前目錄下
plt.savefig('bar.png')
比二,比二環(huán)少一環(huán)的是幾環(huán)?--不清楚?那畫個環(huán)形圖look一look。
import matplotlib.pyplot as plt
#圖片大小設(shè)置為:900*600
plt.rcParams['figure.figsize'] = (9.0, 6.0)
#生成數(shù)據(jù)
share_laptop = [0.8, 0.2]
colors = ['c', 'lightgray']
#一個環(huán)
wedges1, texts1, autotexts1 = plt.pie(share_laptop,
autopct = '',
radius = 1,
pctdistance = 0.85,
colors = colors,
startangle = 180,
textprops = {'color': 'w'},
wedgeprops = {'width': 0.25, 'edgecolor': 'w'}
)
#存圖片在當(dāng)前目錄下
plt.savefig('circle.png')