python Matplotlib 系列教程(三)——繪制直方圖和條形圖


在本章節我們將學習如何繪制條形圖和直方圖

條形圖與直方圖的區別:
首先,條形圖是用條形的長度表示各類別頻數的多少,其寬度(表示類別)則是固定的;

直方圖是用面積表示各組頻數的多少,矩形的高度表示每一組的頻數或頻率,寬度則表示各組的組距,因此其高度與寬度均有意義。

其次,由於分組數據具有連續性,直方圖的各矩形通常是連續排列,而條形圖則是分開排列。

最后,條形圖主要用於展示分類數據,而直方圖則主要用於展示數據型數據

首先來看一個條形圖的例子:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)

plt.bar([1, 3, 5, 7, 9], [5, 4, 8, 12, 7], label='graph 1')

plt.bar([2, 4, 6, 8, 10], [4, 6, 8, 13, 15], label='graph 2')

# params

# x: 條形圖x軸
# y:條形圖的高度
# width:條形圖的寬度 默認是0.8
# bottom:條形底部的y坐標值 默認是0
# align:center / edge 條形圖是否以x軸坐標為中心點或者是以x軸坐標為邊緣

plt.legend()

plt.xlabel('number')
plt.ylabel('value')

plt.title(u'測試例子——條形圖', FontProperties=font)

plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


【注】如果我們沒有明確選擇一種顏色,雖然我們做了多個圖,但是所有的圖都會看起來一樣,即顏色是一樣。

下面我們看一個直方圖的例子:

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)

salary = [2500, 3300, 2700, 5600, 6700, 5400, 3100, 3500, 7600, 7800,
8700, 9800, 10400]

group = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000]


plt.hist(salary, group, histtype='bar', rwidth=0.8)

plt.legend()

plt.xlabel('salary-group')
plt.ylabel('salary')

plt.title(u'測試例子——直方圖', FontProperties=font)

plt.show()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21


這是一個簡單的工資分布情況圖,可以很直觀的得到例如在2000-3000水平的人數有2人。
---------------------
作者:xjl271314
來源:CSDN
原文:https://blog.csdn.net/xjl271314/article/details/80295935
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM