最近在用python中的matplotlib畫折線圖,遇到了坐標軸 “數字+刻度” 混合顯示、標題中文顯示、批量處理等諸多問題。通過學習解決了,來記錄下。如有錯誤或不足之處,望請指正。
一、最簡單的基本框架如下:已知x,y,畫出折線圖並保存。此時x和y均為數字。
1 # -*- coding: utf-8 -*- 2 3 import matplotlib.pyplot as plt #引入matplotlib的pyplot子庫,用於畫簡單的2D圖 4 import random 5 6 x= range(0,20) 7 y= [random.randint(0,20) for _ in range(20)] 8 9 #建立對象 10 fig = plt.figure(figsize=(8,6)) 11 ax = fig.add_subplot() 12 13 #畫圖 14 plt.plot(x,y,'o-',label=u"線條") #畫圖 15 plt.show() 16 plt.savefig("temp.png")
二、坐標軸增加字母元素:
用到了如下語句和函數【參考:http://matplotlib.org/examples/ticks_and_spines/tick_labels_from_values.html】:
from matplotlib.ticker import FuncFormatter, MaxNLocator
labels = list('abcdefghijklmnopqrstuvwxyz')
def format_fn(tick_val, tick_pos):
if int(tick_val) in xs:
return labels[int(tick_val)]
else:
return ''
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
稍微改動,用到了之前的程序里:
1 # -*- coding: utf-8 -*- 2 3 import matplotlib.pyplot as plt #引入matplotlib的pyplot子庫,用於畫簡單的2D圖 4 5 from matplotlib.ticker import FuncFormatter, MaxNLocator 6 7 import random 8 9 x= range(20) 10 11 y= [random.randint(0,20) for _ in range(20)] 12 13 fig = plt.figure(figsize=(8,6)) 14 ax = fig.add_subplot(111) #建立對象 15 16 labels = [1,2,3,4,5,6,7,8,9,10,'a','b','cc','d','e','f','g','h','*%$','20'] 17 18 19 def format_fn(tick_val, tick_pos): 20 if int(tick_val) in x: 21 return labels[int(tick_val)] 22 else: 23 return '' 24 25 ax.xaxis.set_major_formatter(FuncFormatter(format_fn)) 26 ax.xaxis.set_major_locator(MaxNLocator(integer=True)) 27 28 plt.plot(x,y,'o-',label=u"線條") #畫圖 29 plt.show() 30 plt.savefig("temp.png")
這樣坐標軸既可以含有字符串,同時也可以含有數字。
三、標題等的中文顯示:
用到了如下庫和語句:
from matplotlib.font_manager import FontProperties
font1 = FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=8) #可指定計算機內的任意字體,size為字體大小
plt.title(u"標題",fontproperties=font1)
plt.xlabel(u"x軸)",fontproperties=font1)
plt.ylabel(u"Y軸",fontproperties=font1)
ax.legend(prop=font1, loc="upper right")
這樣用到上面程序里,則可以顯示中文:
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt #引入matplotlib的pyplot子庫,用於畫簡單的2D圖 from matplotlib.ticker import FuncFormatter, MaxNLocator import random from matplotlib.font_manager import FontProperties x= range(20) y= [random.randint(0,20) for _ in range(20)] fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) #建立對象 labels = [1,2,3,4,5,6,7,8,9,10,'a','b','cc','d','e','f','g','h','*%$','20'] def format_fn(tick_val, tick_pos): if int(tick_val) in x: return labels[int(tick_val)] else: return '' ax.xaxis.set_major_formatter(FuncFormatter(format_fn)) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) #可指定計算機內的任意字體,size為字體大小 font1 = FontProperties(fname=r"c:\windows\fonts\simsun.ttc",size=20) plt.title(u"標題",fontproperties=font1) plt.xlabel(u"x軸",fontproperties=font1) plt.ylabel(u"Y軸",fontproperties=font1) plt.plot(x,y,'o-',label=u"線條") #畫圖 ax.legend(prop=font1, loc="upper right") plt.show() plt.savefig("temp.png")
畫出的圖如下:
四、不顯示圖片,以便進行批處理:
import matplotlib
matplotlib.use('Agg')
需加在 import matplotlib.pyplot as plt 之前,然后刪掉plt.show()即可。