關於Ubuntu中使用pyplot畫圖不能顯示問題的解決方案記錄

關於 pyplot

pyplot是支持使用Python畫出各種漂亮的科研圖表的庫(全稱matplotlib),有興趣的同學可以去官網閱讀相關的信息以及查看安裝.

測試程序

import numpy as np
import matplotlib.pyplot as plt

x = np.range(0, 5, 0.1) # 50 x-axis points
y = np.sin(x) # y = sin(x)
plt.plot(x, y) 
plt.show()

問題

在Ubuntu中運行程序:

python test1.py

結果沒有顯示繪圖結果。通過google得知是因爲Ubuntu中matplotlib的默認後端是agg,而agg是沒有繪圖能力的。

解決方案

1. 下載 TKinter

sudo apt-get install tk-dev

2. 重寫程序

import numpy as np

import matplotlib as mpl
mpl.use("TkAgg") # Use TKAgg to show figures

import matplotlib.pyplot as plt

x = np.range(0, 5, 0.1) # 50 x-axis points
y = np.sin(x) # y = sin(x)
plt.plot(x, y) 
plt.show() 
plt.savefig("temp.png") # save figure
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章