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

昨天學習pandas和matplotlib的過程當中, 在jupyter notebook遇到ImportError: matplotlib is required for plotting錯誤, 如下是解決該問題的具體描述, 在此記錄, 給後面學習的朋友提供一個參考. python

環境

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 plottingui

解決思路

1. 不能導入matplotlib?在cmd命令窗口下確認:
spa

沒有報錯, 說明安裝成功, 並且可以被成功導入.3d

2. 嘗試其餘方式: 以前用的是pandas中plot()方法繪圖, 換成matplotlib.pyplot中的plot()方法code

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中可以成功運行:blog

再次運行pandas的plot()方法, 仍然報錯, 並且再次檢查沒有發現語句中存在錯誤.ip

那麼問題來了, 爲何pandas中的plot()方法不能用?pycharm

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有時能更快解決問題.

相關文章
相關標籤/搜索