簡體   English   中英

matplotlib 軸標簽的奇怪錯誤

[英]Strange error with matplotlib axes labels

我對 Python 和編程非常陌生,所以如果我遺漏了一些明顯的東西,請提前道歉。 我正在嘗試繪制圖形並標記軸,但每次嘗試標記 y 軸時都會引發異常。 我在一個新腳本中編寫了下面的代碼,以確保問題不是來自模塊中的其他地方。 我正在使用 Python 3.4。

from numpy import *
from matplotlib import *

a = [1, 2, 3, 4, 5]
b = [2, 3, 2, 3, 2]
pyplot.plot(a, b)
pylab.xlabel("Time")
pylab.ylabel("Speed")

每次,我都會收到最后一行的錯誤 'TypeError: 'str' object is not callable'。 如果我將 y 更改為 x,則一切正常。 如果我將 x 更改為 ay,則會出現相同的錯誤。 但是, ylabel 出現在 ylabel 的下拉列表中,因此該函數確實存在,並且文檔說字符串是唯一必要的參數,與 xlabel 完全一樣 (matplotlib.pyplot.ylabel(s, *args, **kwargs) 和matplotlib.pyplot.xlabel(s, *args, **kwargs))。 這到底是怎么回事?

我在 iPython notebook 中工作時遇到了同樣的問題。

我認為它可以重新創建如下:

import matplotlib.pyplot as plt
plt.ylabel = 'somestring' # oh wait this isn't the right syntax.
... 
plt.ylabel('somestring') # now this breaks because the function has been turned into a string

重新啟動內核或重新導入庫會將 plt.ylabel 恢復為函數。

編輯:此代碼適用於干凈運行,但您可能已更改ylabel ,在這種情況下,重新啟動應該可以修復它,正如@wolfins回答的那樣(檢查該答案)

恐怕我不能告訴你出了什么問題,因為它在這里工作正常。 下面的代碼運行沒有錯誤,並顯示帶有正確標簽的圖。

from matplotlib import pyplot, pylab
a = [1, 2, 3, 4, 5]
b = [2, 3, 2, 3, 2]
pyplot.plot(a, b)
pylab.xlabel("Time")
pylab.ylabel("Speed")
pyplot.show()

如果這對您不起作用,也許您可​​以嘗試使用圖形和軸對象,如下所示

from matplotlib.pyplot import subplots, show
a = [1, 2, 3, 4, 5]
b = [2, 3, 2, 3, 2]
fig, ax = subplots()
ax.plot(a, b)
ax.set_xlabel("Time")
ax.set_ylabel("Speed")
show()

不能解決根本問題(這很難,因為我無法重現它),但也許它至少可以達到您的目的。

我剛遇到這種情況。 似乎我所做的是為 xlab 和 ylab分配一個字符串,例如:

plt.xlab = 'string'
plt.ylab = 'string'

這破壞了 xlab 和 ylab 以至於你不能再調用它們,因為它們現在實際上是字符串,而不是函數。

同樣,我使用的是 Jupyter,我不得不殺死 Jupyter 並從頭開始重新運行它來解決這個問題。

奇怪的是,重新導入庫,而籽粒仍然運行沒有工作。

這通常會發生,如果您分配 Xlabel 值而不是調用 . 例如:如果您想將 Xlabel 設置為“X-DUMMY”。 你需要使用

plt.xlabel("X-DUMMY")

但如果你按照下面的方式做,就會出錯。

plt.xlabel= "X-DUMMY"

你會得到這個錯誤。 即使你糾正它說。

plt.xlabel("X-DUMMY") 

除非您重新啟動內核,否則此問題會重復出現。

原因是, plt.xlabel 是一個函數。 在 python 函數中是一流的對象。一旦你分配

 plt.xlabel= "X-DUMMY" 

它被轉換為字符串。 稍后當你嘗試時,它會拋出錯誤

'TypeError: 'str' 對象不可調用'。

您可以在賦值前后使用type(plt.xlabel)來嘗試。 查看它的數據類型。

我保存了檢查點並停止了 ipython 筆記本。 然后我重新啟動它解決了問題。

我在 jupyter notebook 中也遇到過同樣的問題,所以如果你也遇到過這樣的問題,只需重新啟動內核就可以修復它,你的代碼中沒有任何語法錯誤。

這可能會幫助您:

# 0. Import matplotlib and get it ready
%matplotlib inline
import matplotlib.pyplot as plt

# 1. Prepare data
x = [1,2,3,4]
y = [10,20,30,40]

# 2. Setup plot
fig, ax = plt.subplots(figsize=(8,8)) # width & height 

# 3. Plot the data
ax.plot(x,y)

# 4. Customize Plot
ax.set(title="Simple Plot", 
        xlabel="X - Put your X label TITLE here",
        ylabel="Y - Put your y label TITLE here")


# 5. Display
plt.show()

如果你在贏可能你沒有安裝正確版本的 matplotlib

你需要小心你擁有哪個版本的 python 以及你需要在你的計算機上擁有那個版本的 matplotlib

下載: https ://pypi.python.org/pypi/matplotlib/ Windows 用戶:python -m pip install --user matplotlib-2.1.0-cp36-cp36m-win_amd64.whl

在文件名中,您將 se cp36 == python 3.6, cp27 == python 2.7,始終首先檢查計算機上的 python 版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM