python中matplotlib畫折線圖實例(座標軸數字、字符串混搭及標題中文顯示)

最近在用python中的matplotlib畫折線圖,遇到了座標軸 「數字+刻度」 混合顯示、標題中文顯示、批量處理等諸多問題。經過學習解決了,來記錄下。若有錯誤或不足之處,望請指正。html

1、最簡單的基本框架以下:已知x,y,畫出折線圖並保存。此時x和y均爲數字。python

 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")

2、座標軸增長字母元素:windows

用到了以下語句和函數【參考:http://matplotlib.org/examples/ticks_and_spines/tick_labels_from_values.html】:框架

from matplotlib.ticker import FuncFormatter, MaxNLocator dom

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))spa

稍微改動,用到了以前的程序裏:code

 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")

這樣座標軸既能夠含有字符串,同時也能夠含有數字。

3、標題等的中文顯示:

用到了以下庫和語句:

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")


畫出的圖以下:

4、不顯示圖片,以便進行批處理:

import matplotlib
matplotlib.use('Agg')

需加在 import matplotlib.pyplot as plt 以前,而後刪掉plt.show()便可。

相關文章
相關標籤/搜索