在 python 2.6.5 上运行以下简单示例代码时遇到问题。 我已经寻找了无效文字问题的其他解决方案,在我看来,当 python 假设它正在绘制的数据是整数并尝试迭代数据时,通常会发生这种情况。然而,当创建图形对象时,似乎在此之前就出现了此错误。我对此可能是错误的,并且希望有人指出我正确的方向。
import matplotlib.pyplot as plt
import numpy as np
x=np.array([1,2,3,4,5,6,7])
y=np.sin(x)
fig = plt.figure('test figure')
sub1=fig.add_subplot(1,1,1)
sub1.plot(x,y)
生成以下错误
Traceback (most recent call last):
File "C:\Users\u999999\Desktop\code\simple_example.py", line 7, in <module>
fig = plt.figure('test figure')
File "C:\Python\lib\site-packages\matplotlib\pyplot.py", line 241, in figure
num = int(num) # crude validation of num argument
ValueError: invalid literal for int() with base 10: 'test figure'
从评论中添加
我使用的是 matplotlib 版本 0.99.3rc1
最佳答案
您尝试访问的功能正在传入 a text label as num
。原来只能在这里输入数字,现在可以输入数字或字符串标签。
此功能自 this commit 起可用2011 年 6 月。第一个发行版本是 version 1.1.0 。您说您使用的是 0.99.3rc2 版本 - 所以该功能将不可用。我最好的建议是从那个(相当旧的!)版本升级,除非有非常充分的理由不这样做。
<小时/>详细信息
允许您传递字符串代替整数的代码行是 here下面复制了一小段代码来阐明这一点 - matplotlib.pyplot.figure() 的第一个参数被命名为 num 并默认为 None >:
#snippet from matplotlib.pyplot.figure()
if num is None:
num = next_num
elif is_string_like(num):
figLabel = num
allLabels = get_figlabels()
if figLabel not in allLabels:
if figLabel == 'all':
warnings.warn("close('all') closes all existing figures")
num = next_num
else:
inum = allLabels.index(figLabel)
num = allnums[inum]
关于python - 带有标题的 plt.figure() 给出错误 : invalid literal for int() with base 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586501/