昨天學習pandas和matplotlib的過程中, 在jupyter notebook遇到ImportError: matplotlib is required for plotting錯誤, 以下是解決該問題的具體描述, 在此記錄, 給后面學習的朋友提供一個參考.
環境
win8.1, python3.7, jupyter notebook
問題描述
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv") 4 df.plot(x = "Year", y = "Agriculture") 5 plt.xlabel("Year") 6 plt.ylabel("Percentage") 7 plt.show()
在jupyter notebook中執行上述代碼, 拋出以下錯誤:
ImportError: matplotlib is required for plotting
解決思路
1. 不能導入matplotlib?在cmd命令窗口下確認:

沒有報錯, 說明安裝成功, 而且能夠被成功導入.
2. 嘗試其他方式: 之前用的是pandas中plot()方法繪圖, 換成matplotlib.pyplot中的plot()方法
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv") 4 df_year, df_Agriculture = df["Year"], df["Agriculture"] 5 plt.plot(df_year, df_Agriculture,"-", color = "r", linewidth = 5) 6 plt.show()
在jupyter notebook中能夠成功運行:

再次運行pandas的plot()方法, 仍然報錯, 而且再次檢查沒有發現語句中存在錯誤.
那么問題來了, 為什么pandas中的plot()方法不能用?
3. 換IDE試試, 看看在pycharm中能不能運行:
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv") 4 df.plot(x = "Year", y = "Agriculture") 5 plt.xlabel("Year") 6 plt.ylabel("Percentage") 7 plt.show()

在pycharm中能夠成功運行, 而在jupyter notebook中不能運行, 看起是IDE的問題, 那么兩者存在什么差異呢:
就我個人電腦而言, pycharm是我剛剛啟動的(安裝好matplotlib后), 而jupyter notebook已經好幾天沒有關閉過了(安裝matplotlib前后都沒有關閉過), 為了確保兩者條件統一, 試着重啟下jupyter notebook.
重啟jupyter notebook成功之后再次運行代碼:
1 import pandas as pd 2 import matplotlib.pyplot as plt 3 df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv") 4 df.plot(x = "Year", y = "Agriculture") 5 plt.xlabel("Year") 6 plt.ylabel("Percentage") 7 plt.show()
能夠成功顯示:

看起來問題出在: 安裝matplotlib之后沒有重啟jupyter notebook.
總結
個人猜想: 在使用pandas中的plot()方法時, matplotlip里的pyplot繪圖框架僅僅是用來展示圖形的, 而要想讓兩者實現交互, 那應該確保在啟動IDE之前兩者都被成功安裝.
如果在之后遇到類似問題, 在確保代碼無誤的情況下, 直接嘗試重啟下IDE有時能更快解決問題.
