資料分析之matplotlib篇
文章目錄
- 資料分析之matplotlib篇
- matplotlib簡介
- matplotlib基礎
- 繪制多次圖形和不同差異圖形
- 常用統計圖對比
- 繪制散點圖
- 繪制條形圖
- 繪制基本條形圖
- 繪制多次條形圖
- 繪制直方圖
- 屬性設定
- 1、位置`loc`
- 2、線型`linestyle`
- 3、折線點型`marker`
- 其他圖形繪制
- 繪圖網站推薦
- 參考資料
matplotlib簡介
matplotlib官網
資料分析:將大量的資料進行統計和整理,得出結論,為后序的決策提供資料支持
學習matplotlib?
- 能將資料進行可視化,更直觀的呈現
- 使資料更加客觀、更具說服力
matplotlib:最流向的python底層繪圖庫,主要做資料可視化圖表,名字取材于MATLIB,模仿它構建,
matplotlib基礎
簡單示例
from matplotlib import pyplot as plt
import random
#解決中文顯示問題
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默認字體
x = range(0, 120)
y = [random.randint(20, 35) for i in range(0, 120)]
#設定圖片大小(影像模糊的時候可以傳入dpi引數,讓圖片更加清晰)
fig = plt.figure(figsize=(11, 8), dpi=80)
#繪圖
plt.plot(x, y)
#調整x的刻度
_xtick_labels = ["10點{}分".format(i * 10) for i in range(6)]
_xtick_labels += ["11點{}分".format(i * 10) for i in range(6)]
#rotation刻度字體旋轉的度數
plt.xticks(list(x)[::10], _xtick_labels, rotation=45)
#添加描述資訊
plt.xlabel("時間")
plt.ylabel("溫度/℃")
plt.title("10點到12點每分鐘的氣溫變化情況")
#保存
plt.savefig("./簡單示例t1.png")
plt.show()
圖示如下

繪制多次圖形和不同差異圖形
假如在同一張圖上繪制你和朋友11歲至31歲的聚會情況
from matplotlib import pyplot as plt
import random
#解決中文顯示問題
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默認字體
y_1 = [1, 0, 1, 1, 2, 4, 3, 2, 3, 4, 4, 5, 6, 5, 4, 3, 3, 1, 1, 1]
y_2 = [1, 0, 3, 1, 2, 2, 3, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]
x = range(11, 31)
#設定圖片大小
fig = plt.figure(figsize=(12, 5), dpi=80)
#繪圖
"""
繪制時可指定
color = 'r' 線條顏色
linestyle = '--' 線條風格
linewidth = 5 線條粗細
alpha = 0.5 透明度
"""
plt.plot(x, y_1, label="自己", color="orange")
plt.plot(x, y_2, label="同桌", color="cyan")
#設定的刻度
_xtick_labels = ["{}歲".format(i) for i in x]
plt.xticks(x, _xtick_labels)
plt.yticks(range(0, 9))
#繪制網格
plt.grid(alpha=0.5, linestyle=":")
#添加圖例
plt.legend(loc="upper right")
#添加描述資訊
plt.xlabel("年齡")
plt.ylabel("聚會/次")
plt.title("11歲到26歲每年聚會情況")
plt.show()
圖示如下

常用統計圖對比
-
折線圖:以折線的上升或下降來表示統計數量的增減變化的統計圖
特點:能夠顯示資料的變化趨勢,反應事物的變化情況(變化) -
直方圖:由一系列高度不等的縱向條紋或線段表示資料分布的情況,
一般用橫軸表示資料范圍,縱軸表示分布情況
特點:繪制連續的資料,展示一組或者多組資料的分布情況(統計) -
條形圖:排列在作業表的行或列中的資料可以繪制到條形圖中,
特點:繪制離散的資料,能夠一眼看出各個資料的大小,比較資料之間的差別(統計) -
散點圖:用兩組資料構成多個坐標點,考察坐標點的分布,
判斷兩變數之間是否存在某種關聯或總結坐標點的分布模式,
特點:判斷變數之間是否存在數量關系趨勢,展示離群點(分布規律)
繪制散點圖
代碼示例
from matplotlib import pyplot as plt
#解決中文顯示問題
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默認字體
y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,
21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,
20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]
x_3 = range(1, 32)
x_10 = range(51, 82)
#設定圖形大小
plt.figure(figsize=(11, 7), dpi=80)
#使用scatter方法繪制散點圖,和之前繪制折線圖的唯一區別
plt.scatter(x_3, y_3, label='3月份')
plt.scatter(x_10, y_10, label='10月份')
#調整x的刻度
_x = list(x_3) + list(x_10)
_xtick_labels = ["3月{}日".format(i) for i in x_3]
_xtick_labels += ["10月{}日".format(i - 50) for i in x_10]
plt.xticks(_x[::5], _xtick_labels[::5], rotation=45)
#添加圖例
plt.legend(loc="upper right")
#添加描述資訊
plt.xlabel("時間")
plt.ylabel("溫度")
plt.title("標題")
#展示
plt.show()
圖示如下

繪制條形圖
繪制基本條形圖
代碼示例
#繪制橫著的條形圖
from matplotlib import pyplot as plt
#解決中文顯示問題
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默認字體
a = ["低俗小說", "速度與激情8", "燃情歲月", "辛德勒的名單", "勇敢的心", "亂世佳人",
"燦爛人生", "美麗人生", "生活多美好", "教父", "霍位元人", "泰坦尼克號"]
b = [36.01, 25.90, 17.53, 29.60, 42.40, 33.53, 37.80, 40.52, 60.43, 57.33, 43.90, 50.99]
#設定圖形大小
plt.figure(figsize=(10, 7), dpi=80)
#繪制條形圖
plt.barh(range(len(a)), b, height=0.4, color='cyan')
#設定字串到x軸
plt.yticks(range(len(a)), a)
#若繪制豎著的條形圖,相應代碼如下
#plt.bar(range(len(a)), b, width=0.3)
#plt.xticks(range(len(a)), a, rotation=40)
plt.grid(alpha=0.4, color='pink')
#添加描述資訊
plt.ylabel("電影")
plt.xlabel("票房/億")
plt.title("xxx年電影票房統計")
plt.show()
圖示如下:

繪制多次條形圖
代碼示例
from matplotlib import pyplot as plt
#解決中文顯示問題
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默認字體
a = ["傲慢與偏見", "茶花女", "亂世佳人", "理智與情感"]
b_16 = [1746, 324, 4466, 389]
b_15 = [1247, 158, 2039, 189]
b_14 = [2490, 389, 3900, 289]
bar_width = 0.2
x_14 = list(range(len(a)))
x_15 = [i + bar_width for i in x_14]
x_16 = [i + bar_width * 2 for i in x_14]
#設定圖形大小
plt.figure(figsize=(10, 7), dpi=80)
plt.bar(x_14, b_14, width=bar_width, label="9月14日")
plt.bar(x_15, b_15, width=bar_width, label="9月15日")
plt.bar(x_16, b_16, width=bar_width, label="9月16日")
#設定圖例
plt.legend(loc="upper right")
#設定x的刻度
plt.xticks(x_15, a)
plt.show()
圖示如下:

繪制直方圖
簡單示例
#180部門電影時長
from matplotlib import pyplot as plt
import random
#解決中文顯示問題
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默認字體
a = [random.randint(0, 100) + 90 for i in range(1, 181)]
#計算組數
d = 5 #組距
num_bins = (max(a) - min(a)) // d
#設定圖形大小
plt.figure(figsize=(11, 6 ), dpi=80)
plt.hist(a, num_bins, normed=True)
#設定x軸的刻度
plt.xticks(range(min(a), max(a) + d, d))
plt.grid(alpha=0.4, color='cyan')
plt.show()
圖示如下:

屬性設定
1、位置loc
loc='center left' 等價于loc=6
'best': 0,
'upper right': 1,
'upper left': 2,
'lower left': 3,
'lower right': 4,
'right': 5,
'center left': 6,
'center right': 7,
'lower center': 8,
'upper center': 9,
'center': 10,
2、線型linestyle
- 實線
-- 虛線
-. 形式即為-.
: 細小的虛線
3、折線點型marker
s--方形
h--六角形
H--六角形
*--*形
+--加號
x--x形
d--菱形
D--菱形
p--五角形
其他圖形繪制
matplotlib官網示例
如下圖所示

隨便點進去一個你感興趣的圖示,其中有完整的繪圖代碼,可更改其資料,如
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
# Fixing random state for reproducibility
np.random.seed(19680801)
NUM = 200
ells = [Ellipse(xy=np.random.rand(3) * 10,
width=np.random.rand(), height=np.random.rand(),
angle=np.random.rand() * 360)
for i in range(NUM)]
fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
for e in ells:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(np.random.rand())
e.set_facecolor(np.random.rand(3))
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
plt.show()
效果圖如下

繪圖網站推薦
- d3js.org/
- chartjs.org/
- https://www.highcharts.com/
- seaborn.pydata.org/
- echarts.apache.org/
參考資料
https://matplotlib.org/
【python教程】資料分析——numpy、pandas、matplotlib
matplotlib輕松解決中文亂碼問題
python畫圖的圖例legend設定,
Python資料分析:折線圖和散點圖的繪制
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/304077.html
標籤:區塊鏈
