1. 程式人生 > >python 使用matplotlib畫圖

python 使用matplotlib畫圖

#!/usr/bin/python
# encoding=utf-8

import sys
import matplotlib.pyplot as plt

reload(sys)
sys.setdefaultencoding('utf-8')

x = [1, 2, 3]
y = [5, 7, 4]

x2 = [1, 2, 3]
y2 = [10, 14, 12]

x3 = [5, 6, 7]
y3 = [10, 14, 12]

# 散點和折線圖
plt.figure('Line')  # 指定圖表名稱
plt.plot(x, y, '.', label='First')  # 散點圖,以'.'作為形狀, 名字為First
plt.plot(x2, y2, label='Second') # 折線圖, 名字為Second plt.xlabel('Plot Number') # 建立X軸的名稱 plt.ylabel('Important var') # 建立Y軸的名稱 plt.xlim(-2.5, 2.5) # 設定X軸座標範圍 plt.ylim(-1, 1) # 設定Y軸座標範圍 plt.title('Scatter Diagram\nLine Chart') # 建立圖的標題 plt.legend() # 生成預設圖例 # 條形圖 plt.figure('Bar') # 指定圖表名稱 plt.bar(x,
y, label='One') # 建立條形圖,命名為One plt.bar(x3, y3, label='Two', color='g') # 建立條形圖, 顏色為g:綠色, r:紅色, b:藍色,也可以用十六進位制顏色程式碼:#000011 plt.legend() # 生成預設圖例 plt.xlabel('Bar Number') # 建立X軸的名稱 plt.ylabel('Bar Height') # 建立Y軸的名稱 plt.title('Bar Chart') # 建立圖的標題 # 直方圖: 直方圖非常像條形圖,傾向於通過將區段組合在一起來顯示分佈 plt.figure('Histogram'
) # 指定圖表名稱 population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48] bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130] plt.hist(population_ages, bins, histtype='bar', rwidth=0.8) plt.xlabel('Histogram Number') # 建立X軸的名稱 plt.ylabel('Histogram Height') # 建立Y軸的名稱 plt.title('Histogram Chart') # 建立圖的標題 plt.legend() # 生成預設圖例 # 散點圖 plt.figure('Scatter') # 指定圖表名稱 x4 = [1, 2, 3, 4, 5, 6, 7, 8] y4 = [5, 2, 4, 2, 1, 4, 5, 2] plt.scatter(x4, y4, label='Scatter', color='k', s=25, marker="o") plt.xlabel('x') plt.ylabel('y') plt.title('Scatter Chart') plt.legend() # 堆疊圖 plt.figure('Stack') # 指定圖表名稱 days = [1, 2, 3, 4, 5] sleeping = [7, 8, 6, 11, 7] eating = [2, 3, 4, 3, 2] working = [7, 8, 7, 2, 2] playing = [8, 5, 7, 8, 13] plt.plot([], [], color='m', label='Sleeping', linewidth=5) plt.plot([], [], color='c', label='Eating', linewidth=5) plt.plot([], [], color='r', label='Working', linewidth=5) plt.plot([], [], color='k', label='Playing', linewidth=5) plt.stackplot(days, sleeping, eating, working, playing, colors=['m', 'c', 'r', 'k']) plt.xlabel('x') plt.ylabel('y') plt.legend() plt.title('Stack Chart') # 餅圖 plt.figure('Pie') # 指定圖表名稱 slices = [7, 2, 2, 13] activities = ['sleeping', 'eating', 'working', 'playing'] cols = ['c', 'm', 'r', 'b'] plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow=True, explode=(0, 0.1, 0, 0), autopct='%1.1f%%') plt.title('Pie Chart') plt.show() # 畫圖