1. 程式人生 > >解決在jupyter notebook中遇到的ImportError: matplotlib is required for plotting問題

解決在jupyter notebook中遇到的ImportError: matplotlib is required for plotting問題

昨天學習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. 沒有安裝成功?在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有時能更快解決問題.