10分鐘入門Matplotlib:數據可視化介紹&使用教程

一張圖勝過千言萬語",對於數據來說同樣地,"一張可視化的圖片勝過一張複雜的數據表格或報告"。

Matplotlib介紹

數據可視化是數據科學家需要掌握的必備技能之一。使用可視化技術可以理解和解決大多數業務問題。可視化主要包括探索性數據分析(EDA)和圖形繪製。有效的可視化有助於用戶瞭解數據中的模式,並有效地解決業務問題。可視化的另一個優點是能將複雜數據簡化為易於理解的形式。

人們總是覺得圖像比文本更容易理解,因此可視化是分析和解釋數據的最佳手段,它能幫助用戶輕鬆地理解大量的信息。數據可視化也有助於人們理解趨勢、相關性、模式、分佈等信息。

在數據可視化領域的眾多工具和技術中,python是最常用的。Python為數據可視化提供了多個庫,其中最常用的有:

· Matplotlib

· Seaborn

· Pandas visualisation

· Plotly

本文檔將有助於你瞭解在業界被廣泛使用的matplotlib庫。Matplotlib具有豐富的圖形功能,而且容易上手。本文主要介紹不同的圖形功能,包括一些語法等。

Matplotlib的安裝

matplotlib庫有多種安裝方法。最簡單的安裝matplotlib的方式是下載Anaconda包。因為Anaconda會默認安裝Matplotlib,不需要你進行任何額外的步驟。

· 從anaconda的官方網站下載anaconda軟件包

· 為了安裝matplotlib,打開anaconda提示符並運行以下命令

<code>pip install matplotlib/<code>

or

<code>conda install matplotlib/<code>

· 在Jupyter notebook中運行以下命令以驗證matplotlib是否正確安裝

<code>import matplotlib
matplotlib.__version__/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程


如何使用Matplotlib

在使用matplotlib之前,我們需要在Jupyter notebook中使用'import'方法來導入這個包。PyPlot是matplotlib中最常用的數據可視化模塊,通常使用PyPlot就足以滿足可視化的需求。

<code># import matplotlib library as mpl
import matplotlib as mpl

#import the pyplot module from matplotlib as plt (short name used for referring the object)
import matplotlib.pyplot as plt/<code>


10分鐘入門Matplotlib:數據可視化介紹&使用教程


Matplotlib、Pyplot和Python之間的關係

· Python是一種非常流行的編程語言,可以用於web開發、數學和統計分析。Python可以在大多數平臺上工作,而且使用起來也很簡單。

· Python有很多庫可以調用,用於可視化和數據分析的庫主要以下幾種。

· NumPy

· Pandas

· Matplotlib

· Seaborn

· Plotly

· SciKit-Learn

· 正如您所看到的,這裡麵包括matplotlib,它是使用python開發的。這個庫被廣泛用於數據可視化。

· PyPlot是matplotlib中的一個模塊,它提供類似於MATLAB的交互體驗。MATLAB被廣泛用於工業界中的統計分析。但MATLAB是一種需要許可的軟件,且價格不菲。而PyPlot是一個開源模塊,為python用戶提供類似MATLAB的功能。總之,PyPlot在開源環境中被視為MATLAB的替代品。

繪製一個簡單的圖像

在這裡,我們將使用NumPy生成的隨機數來繪製一個簡單的圖像。創建圖像最簡單的方法是使用' plot() '方法。為了生成一個圖像,我們需要兩個座標軸(X)和(Y),因此我們使用Numpy中的' linspace() '方法生成兩個隨機數列。

<code># import the NumPy package
import numpy as np

# generate random number using NumPy, generate two sets of random numbers and store in x, y
x = np.linspace(0,50,100)
y = x * np.linspace(100,150,100)

# Create a basic plot
plt.plot(x,y)/<code>


10分鐘入門Matplotlib:數據可視化介紹&使用教程

生成的圖像如下圖所示:


10分鐘入門Matplotlib:數據可視化介紹&使用教程

為圖像添加更多元素

上面生成的圖還缺少一些東西,讓我們試著為它添加不同的元素,以便更好地解釋這個圖。可以為其添加的元素包括title、x-Label、y-label、x-limits、y-limits。

<code># set different elements to the plot generated above 

# Add title using 'plt.title'
# Add x-label using 'plt.xlabel'
# Add y-label using 'plt.ylabel'
# set x-axis limits using 'plt.xlim'
# set y-axis limits using 'plt.ylim'
# Add legend using 'plt.legend'/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># add color, style, width to line element
plt.plot(x, y, c = 'r', linestyle = '--', linewidth=2)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># add markers to the plot, marker has different elements i.e., style, color, size etc.,
plt.plot (x, y, marker='*', markersize=3, c='g')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># add grid using grid() method
Plt.grid(True)

# add legend and label
plt.legend()/<code>


10分鐘入門Matplotlib:數據可視化介紹&使用教程

圖像自定義:

· 色彩

· b –藍色

· c –青色

· g –綠色

· k –黑色

· m –洋紅色

· r –紅色

· w –白色

· y –黃色

· 可以使用十六進制或RGB格式

· 線型

· '-' : 實線

· '--':虛線

· '-。':點劃線

· ':'–虛線

· 標記樣式

· 。–點標記

· ,–像素標記

· v –三角形向下標記

· ^ –三角形向上標記

·

· >–三角形右標記

· 1 –三腳架下降標記

· 2 –三腳架向上標記

· 3 –三腳架左標記

· 4 –三腳架右標記

· s –方形標記

· p –五邊形標記

· –星形標記

· 其他配置屬性

· color or c

· linestyle

· linewidth

· marker

· markeredgewidth

· markeredgecolor

· markerfacecolor

· markersize

在一張圖中繪製多個函數

在某些情況下,出於特殊目的,用戶可能必須在單個圖像中顯示多個函數。例如,零售商想知道最近12個月中兩家分店的銷售趨勢,而他希望在同一個座標軸裡查看兩家商店的趨勢。


讓我們在一張圖中繪製兩條線sin(x)和cos(x),並添加圖例以瞭解哪一條線是什麼。

<code># lets plot two lines Sin(x) and Cos(x)
# loc is used to set the location of the legend on the plot
# label is used to represent the label for the line in the legend
# generate the random number

x= np.arange(0,1500,100)
plt.plot(np.sin(x),label='sin function x')
plt.plot(np.cos(x),label='cos functon x')
plt.legend(loc='upper right')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># To show the multiple plots in separate figure instead of a single figure, use plt.show() statement before the next plot statement as shown below
x= np.linspace(0,100,50)
plt.plot(x,'r',label='simple x')
plt.show()
plt.plot(x*x,'g',label='two times x')
plt.show()
plt.legend(loc='upper right')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程


創建子圖

在某些情況下,如果我們要給股東彙報公司最近的情況,我們需要在一個圖中顯示多個子圖。這可以通過使用matplotlib庫中的subplot來實現。例如,一家零售店有6家分店,經理希望在一個展示窗口中看到6家商店的每日銷售額並進行比較。這可以通過subplots將報表的行和列進行可視化處理。

<code># subplots are used to create multiple plots in a single figure
# let's create a single subplot first following by adding more subplots
x = np.random.rand(50)
y = np.sin(x*2)/<code>


<code>#need to create an empty figure with an axis as below, figure and axis are two separate objects in matplotlib
fig, ax = plt.subplots()

#add the charts to the plot
ax.plot(y)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># Let's add multiple plots using subplots() function
# Give the required number of plots as an argument in subplots(), below function creates 2 subplots
fig, axs = plt.subplots(2)

#create data
x=np.linspace(0,100,10)

# assign the data to the plot using axs
axs.plot(x, np.sin(x**2))
axs.plot(x, np.cos(x**2))

# add a title to the subplot figure
fig.suptitle('Vertically stacked subplots')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># Create horizontal subplots
# Give two arguments rows and columns in the subplot() function
# subplot() gives two dimensional array with 2*2 matrix
# need to provide ax also similar 2*2 matrix as below

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

# add the data to the plots
ax1.plot(x, x**2)
ax2.plot(x, x**3)
ax3.plot(x, np.sin(x**2))
ax4.plot(x, np.cos(x**2))

# add title
fig.suptitle('Horizontal plots')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># another simple way of creating multiple subplots as below, using axs
fig, axs = plt.subplots(2, 2)

# add the data referring to row and column
axs.plot(x, x**2,'g')
axs.plot(x, x**3,'r')
axs.plot(x, np.sin(x**2),'b')
axs.plot(x, np.cos(x**2),'k')

# add title
fig.suptitle('matrix sub plots')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

Figure對象

Matplotlib是一個面向對象的庫,包括對象、方法等。我們所繪製的圖也是Figure對象中的類之一。Figure對象是用於顯示圖的容器,可通過調用Figure()函數實現。

· Figsize – (寬, 高)英寸

· Dpi –用於調整每英寸網點數(可根據打印質量進行調整)

· facecolor

· edgecolor

· linewidth

<code># let's create a figure object
# change the size of the figure is 'figsize = (a,b)' a is width and 'b' is height in inches
# create a figure object and name it as fig

fig = plt.figure(figsize=(4,3))

# create a sample data
X = np.array()
Y = X**2

# plot the figure
plt.plot(X,Y)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># let's change the figure size and also add additional parameters like facecolor, edgecolor, linewidth

fig = plt.figure(figsize=(10,3),facecolor='y',edgecolor='r',linewidth=5)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

Axes對象

Axes是指繪製數據的區域,我們可以使用' add_axes() '將Axes添加到圖中。該方法需要以下四個參數:,Left,Bottom,Width,Height

· Left–Axes與圖中左側的距離

· Bottom–Axes與圖中底部的距離

· Width–Axes的寬度

· Height–Axes的高度

Axes的其他屬性:

· Set title using 'ax.set_title()'

· Set x-label using 'ax.set_xlabel()'

· Set y-label using 'ax.set_ylabel()'

<code># lets add axes using add_axes() method
# create a sample data
y =
x1 =
x2 =
# create the figure
fig = plt.figure()
# add the axes
ax = fig.add_axes()
l1 = ax.plot(x1,y,'ys-')
l2 = ax.plot(x2,y,'go--')

# add additional parameters
ax.legend(labels = ('line 1', 'line 2'), loc = 'lower right')
ax.set_title("usage of add axes function")
ax.set_xlabel('x-axix')
ax.set_ylabel('y-axis')
plt.show()/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

Matplotlib中的繪圖類型

Matplotlib有各種各樣的繪圖類型,包括條形圖、折線圖、餅狀圖、散點圖、氣泡圖、瀑布圖、圓形區域圖、堆疊條形圖等,我們將通過一些例子來介紹它們。這些圖的許多屬性都是通用的,如axis, color等,但有些屬性卻是特有的。

條形圖

概述:

條形圖使用水平或垂直方向的長條去表示數據。條形圖用於顯示兩個或多個類別的值,通常x軸代表類別。每個長條的長度與對應類別的計數成正比。

函數:

· 用於顯示條形圖的函數是' plt .bar() '

· bar()函數需要輸入X軸和Y軸的數據

自定義:

plt.bar()函數具有以下參數,可用於配置繪圖:

· Width, Color, edge colour, line width, tick_label, align, bottom,

· Error Bars – xerr, yerr

# lets create a simple bar chart

# x-axis is shows the subject and y -axis shows the markers in each subject

例子:

<code>subject =
marks =
plt.bar(subject,marks)
plt.show()/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code>#let's do some customizations
#width – shows the bar width and default value is 0.8
#color – shows the bar color
#bottom – value from where the y – axis starts in the chart i.e., the lowest value on y-axis shown
#align – to move the position of x-label, has two options 'edge' or 'center'
#edgecolor – used to color the borders of the bar
#linewidth – used to adjust the width of the line around the bar
#tick_label – to set the customized labels for the x-axis

plt.bar(subject,marks,color ='g',width = 0.5,bottom=10,align ='center',edgecolor='r',linewidth=2,tick_label=subject)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># errors bars could be added to represent the error values referring to an array value
# here in this example we used standard deviation to show as error bars
plt.bar(subject,marks,color ='g',yerr=np.std(marks))
# to plot horizontal bar plot use plt.barh() function
plt.barh(subject,marks,color ='g',xerr=np.std(marks))/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程


餅狀圖

概述:

餅狀圖表示每個值相對於所有值之和的比例。餅狀圖上的值以扇形的形式顯示了每個值的百分比貢獻。扇形的角度是根據值的比例計算的。當我們試圖比較總體中的不同部分時,這種可視化效果是最好的。例如,一個銷售經理想要知道一個月裡不同付款類型所佔比例,如現金、信用卡、借記卡、PayPal等應用的支付比例。

函數:

· 用於餅狀圖的函數是' plt.pie() '

· 為了繪製餅狀圖,我們需要輸入一個列表,每個扇形都是先計算列表中的值所佔比例,再轉換成角度得到的

自定義:

plt.pie()函數具有以下參數,可用於配置繪圖。

· labels – 用於顯示每個扇形所屬的類別

· explode – 用於突出扇形

· autopct –用於顯示扇形區域所佔百分比

· shadow –在扇形上顯示陰影

· colours –為扇形設置自定義顏色

· startangle –設置扇形的角度

例子:

<code># Let's create a simple pie plot
# Assume that we have a data on number of tickets resolved in a month
# the manager would like to know the individual contribution in terms of tickets closed in the week
# data
Tickets_Closed =
Agents =

# create pie chart
plt.pie(Tickets_Closed, labels = Agents)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code>#Let's add additional parameters to pie plot
#explode – to move one of the wedges of the plot
#autopct – to add the contribution %

explode =
plt.pie(Tickets_Closed, labels = Agents, explode=explode, autopct='%1.1f%%' )/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

散點圖

概述:

散點圖通過顯示數據點來展示兩列數據之間的關係。繪製散點圖需要兩個變量,一個變量表示X軸位置,另一個變量表示y軸位置。散點圖用於表示變量之間的關聯,通常建議在進行迴歸之前使用。散點圖有助於理解數據的以下信息:

· 兩列數據間的任何關係

· + ve(陽性)關係

· -ve(陰性)關係

函數:

· 用於散點圖的函數是"pl .scatter()"

自定義:

scatter()函數具有以下參數,用於配置繪圖。

· size – 設置點的大小

· color –設置點的顏色

· marker – 標記的類型

· alpha – 點的透明度

· norm –規範化數據(將數據歸一化0至1)

例子:

<code># let's create a simple scatter plot
# generate the data with random numbers
x = np.random.randn(1000)
y = np.random.randn(1000)
plt.scatter(x,y)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># as you observe there is no correlation exists between x and y
# let's try to add additional parameters
# size – to manage the size of the points
#color – to set the color of the points
#marker – type of marker
#alpha – transparency of point

size = 150*np.random.randn(1000)
colors = 100*np.random.randn(1000)
plt.scatter(x, y, s=size, c = colors, marker ='*', alpha=0.7)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程


直方圖

概述:

直方圖是用來了解數據分佈的。它是對連續數據概率分佈的估計。它與上面討論的條形圖相似,但它用於表示連續變量的分佈,而條形圖用於表示離散變量的分佈。每個分佈都有四個不同的特徵,包括

· 分佈中心

· 分佈散佈

· 分佈形狀

· 分佈峰值

直方圖需要兩個輸入,x軸表示bin, y軸表示數據集中每個bin對應值的頻率。每個bin都有一個最小值和最大值的範圍。

函數:

· 繪製直方圖使用的函數是"plt.hist()"

自定義:

函數的具體參數如下,可用於配置繪圖:

· bins – bin的個數

· color-顏色

· edgecolor-邊緣的顏色

· alpha – 顏色透明度

· normed –正則化

· xlim – X軸範圍

· ylim –Y軸範圍

· xticks, yticks-座標軸的刻度

· facecolor-柱的顏色

例子:

<code># let's generate random numbers and use the random numbers to generate histogram
data = np.random.randn(1000)
plt.hist(data)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># let's add additional parameters
# facecolor
# alpha
# edgecolor
# bins

data = np.random.randn(1000)
plt.hist(data, facecolor ='y',linewidth=2,edgecolor='k', bins=30, alpha=0.6)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

<code># lets create multiple histograms in a single plot
# Create random data
hist1 = np.random.normal(25,10,1000)
hist2 = np.random.normal(200,5,1000)

#plot the histogram
plt.hist(hist1,facecolor = 'yellow',alpha = 0.5, edgecolor ='b',bins=50)
plt.hist(hist2,facecolor = 'orange',alpha = 0.8, edgecolor ='b',bins=30)/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

10分鐘入門Matplotlib:數據可視化介紹&使用教程

保存繪圖

使用matplotlib中的"savefig()"函數可將圖保存到本地。圖可以以多種格式保存,如.png、.jpeg、.pdf以及其他支持的格式。

<code># let's create a figure and save it as image
items =
x = np.arange(6)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='items')
plt.title('Saving as Image')
ax.legend()
fig.savefig('saveimage.png')/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

圖像以"saveimage.png"為文件名保存。

<code>#To display the image again, use the following package and commands
import matplotlib.image as mpimg
image = mpimg.imread("saveimage.png")
plt.imshow(image)
plt.show()/<code>
10分鐘入門Matplotlib:數據可視化介紹&使用教程

Matplotlib教程到此結束。

作者: Mr. Sridhar Anchoori

deephub翻譯組:zhangzc


分享到:


相關文章: