1. 程式人生 > >python3繪圖示例6-1(基於matplotlib,繪圖流程介紹及設定等)

python3繪圖示例6-1(基於matplotlib,繪圖流程介紹及設定等)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os

import pylab as py
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mplt

# matplotlib.get_config() 獲取當前配置
# 使用者matplotlib配置檔案路徑
path=mplt.get_configdir()
print(path)

# 當前matplotlib配置檔案路徑
path2=mplt.matplotlib_fname()
print(path2)

# 系統配置檔案存放路徑
path3=os.getcwd()
print(path3)

# 讀取配置檔案內容
p=mplt.rcParams
print(p)

# 中文亂碼處理 正常顯示中文標籤 及正負號
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
plt.rcParams['axes.unicode_minus']=False

# 畫圖流程:建立Figure物件->1個或多個Axes或Subplot物件->呼叫Axies建立各類Artists來畫圖

# # 圖1-正弦圖 餘弦圖
# x=np.linspace(-np.pi,np.pi,256,endpoint=True)
# c,s=np.cos(x),np.sin(x)
#
#
# # matplotlib中可 設定圖片的大小 解析度 線寬 顏色 風格 座標軸 網格屬性 文字屬性 字型屬性等
#
# py.plot(x,c)
# py.plot(x,s)
#
# py.show()

# 這裡使用的是matplotlib.pylab 去畫圖
# 影象 指整個視窗內容 子圖值影象中的各個圖
# 圖2
# 步驟1-建立一個 8*6 的點影象 解析度為 80

# 引數說明
# 影象數量 num=None, # autoincrement if None, else integer from 1-N
# 影象的長和寬 figsize=None, # defaults to rc figure.figsize
# 解析度 dpi=None, # defaults to rc figure.dpi
# 區域背景色 facecolor=None, # defaults to rc figure.facecolor
# 區域邊緣色 edgecolor=None, # defaults to rc figure.edgecolor
# 是否繪製圖像邊緣 # frameon=True,
# FigureClass=Figure,
# clear=False,
# **kwargs
py.figure(8*6,dpi=80)

# 步驟2-設定子圖位置 幾行幾列的網格 第1個引數:1行 第2個引數:1列 第3個引數:圖形在網格的位置
# 多個子圖組成大圖
# fig=plt.figure()->plt.subplot()->plot.plot()->plot.show()

# 子圖懸浮在大圖上
# fig=plt.figure()->ax=fig.add_axes(位置列表)或ax=fig.axes()->ax.plot()->plt.show()
# fig=plt.figure()->fig.add_subplot()->p=plt.Rectangle()多個->fig.add_subplot().add_patch(p)->fig.canvas.draw()->plot.show()

# py.subplot(1,1,1)
py.subplot(111)


# 步驟3-自定義x y軸
# 座標軸物件 axes 可放置在影象的任意位置
# 記號位置設定 Tick Locators 記號格式化操作 Tick Formatters
x=np.linspace(-np.pi,np.pi,256,endpoint=True)
c,s=np.cos(x),np.sin(x)

# 步驟4-1-繪製曲線 顏色 線寬 線的風格(顏色+線型) 大圖對應的小圖標籤 可用$$包裹,如$sin(x)$
py.plot(x,c,color='blue',linewidth=2.5,linestyle='-',label='cosine')
py.plot(x,s,color='red',linewidth=2.5,linestyle='-',label='sine')

# 步驟4-1-給曲線圖上的對應資料點加註釋
# t=2*np.pi/3
# py.plot([t,t],[0,np.cos(t)],color='blue',linewidth=2.5,linestyle='--')
# py.scatter([t,],[np.cos(t),],50,color='blue')
# py.annotate(r'$sin(frac{2\pi}{3}=frac{sqrt{3}{2}$',
# xy=(t,np.sin(t)),xycoords='data',
# xytext=(+10,+30),textcoords='offset points',fontsize=16,
# arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))
#
#
# py.plot([t,t],[0,np.sin(t)],color='red',linewidth=2.5,linestyle='--')
# py.scatter([t,],[np.sin(t),],50,color='red')
# py.annotate(r'$sin(frac{2\pi}{3}=frac{sqrt{1}{2}$',
# xy=(t,np.cos(t)),xycoords='data',
# xytext=(-90,-50),textcoords='offset points',fontsize=16,
# arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2'))

# 註解設定-註解和資料使用相同座標 被註解資料的位置 終點座標 xycoords='data' 註解文字位置,起點座標 xytext=(5,38) 箭頭屬性和風格
# py.annotate('import value',(55,22),xycoords='data',xytext=(5,38),arrowprops=dict(arrowstyle='->'))
# 線的風格 實線 - 破折線 -- 點線 -. 虛線 : 不顯示 None '' ' '

# 線條標記
# 圓圈 o 小菱形 d 菱形 D
# 正方形 s 五邊形 p 六邊形1 h 六邊形2 H 八邊形 8
# 水平線 _ 豎線 | 加號 + 點 . 畫素 , 星號 * x X 無 None '' ' '
# 1角朝上三角形 ^ 1角朝下三角形 v 1角朝左三角形 < 1角朝右三角形 >

# 線的顏色 紅 r 黃 y 白 w 綠 g 藍 b 青 c 洋紅 m 黑 k 支援16進位制'#eeefff'或3元色組(0.3,0.3,0.3)
# 顏色 線寬 線的風格(顏色+線型) 大圖對應的小圖標籤 可用$$包裹,如$sin(x)$
# py.plot(x,c,color='blue',linewidth=2.5,linestyle='-',label='cosine')
# py.plot(x,s,color='red',linewidth=2.5,linestyle='-',label='sine')

# 屬性設定使用set_屬性 pyplot.setp()函式 屬性獲取使用 get_屬性 pyplot.getp()

# 步驟4-2-設定顯示大圖對應的小圖標籤位置
# 小圖標籤設定-起始位置 寬度 高度 圖例位置(左:3-6-2,中:8-10-9,右:4-7-1) 列數 圖例擴充套件至整個座標軸 座標軸和圖例距離
# py.legend(bbox_to_anchor=(0.,1.02,1.,.102),loc=3,ncol=3,mode='expand',borderaxespad=0.)
# py.legend(loc=3)
py.legend(loc='upper left')

# 座標取值範圍
# plt.axis([xmin,xmax,ymin,ymax])

# 步驟5-1-設定橫軸的上下限
py.xlim(-4.0,4.0)

# 步驟5-2-橫軸標記號
# py.xticks(np.linspace(-4,4,9,endpoint=True))
# py.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi])

# 步驟5-3-設定橫軸標號標籤
py.xticks([-np.pi,-np.pi/2,0,np.pi/2,np.pi],[r'$-\pi$',r'$-\pi/2$',r'$0$',r'$+\pi/2$',r'$+\pi$'])

# 步驟5-4-設定縱軸的上下限
py.ylim(-1.0,1.0)

# 步驟5-5-設定縱軸標記號
# py.yticks(np.linspace(-1,1,5,endpoint=True))
# py.yticks([-1,0,+1])

# 步驟5-6-設定縱軸標號標籤
py.yticks([-1,0,+1],[r'$-1$',r'$0$',r'$+1$'])


# 步驟6-1設定圖上文字浮在最上層,方便檢視
# 獲取座標軸物件
ax=py.gca()
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.65,zorder=2))

# 步驟6-2移動脊柱(可省略-移動x y軸 這個看需求,預設的話為常見的x軸和y軸圖)
# 設定對應的邊框是否顯示 及邊框顏色 邊框位置:left right bottom top none
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

# x軸 設定刻度 top bottom both default none 位置 data axes outward
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))

# y軸
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))


# 影象標題
py.title('雙弦圖')

# 步驟7-設定在螢幕上顯示影象
py.show()


# 關閉視窗用 預設無參-關閉當前視窗 all-關閉所有視窗 視窗編號或例項-則關閉指定視窗
# py.close(1)