当我运行以下来自 google colab 中 w3school 的 python 代码时,我得到了“AttributeError:'OutStream'对象没有属性'buffer'”

问题描述 投票:0回答:2

这里提一下我在w3school看到的代码。

    # w3school code
import sys
import matplotlib
matplotlib.use('Agg')

import pandas as pd
import matplotlib.pyplot as plt

health_data = pd.read_csv("data.csv", header=0, sep=",")

health_data.plot(x ='Average_Pulse', y='Calorie_Burnage', kind='line'),
plt.ylim(ymin=0, ymax=400)
plt.xlim(xmin=0, xmax=150)

plt.show()

#Two  lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

如果我使用下面的代码对 google colab 中的 Kaggle 数据集执行上述操作,我会收到错误(AttributeError: 'OutStream' 对象没有属性 'buffer')。

 #Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')

import pandas as pd
import matplotlib.pyplot as plt

health_data = pd.read_csv("/content/drive/MyDrive/India_GDP_Data.csv", header=0, sep=",")

health_data.plot(x ='Year', y='GDP_In_Billion_USD', kind='line'),
plt.ylim(ymin=0, ymax=400)
plt.xlim(xmin=0, xmax=150)

plt.show()

#Two  lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
python object attributes buffer
2个回答
0
投票

我在 W3schools 上也遇到了同样的问题!

在笔记本中使用

matplotlib inline
,如下所示:

%matplotlib inline

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('data.csv')

df.plot()

plt.show()

sys.stdout.flush()

0
投票

我知道这来得太晚了,但我觉得这可能会对以后的其他人有所帮助。 我通过执行以下操作,在 Jupyter Notebook 中从 w3school 获得了相同的代码:

  1. 删除 matplotlib.use('Agg')

  2. 添加 %matplotlib 内联

  3. 将 plt.savefig(sys.stdout.buffer) 更改为 plt.savefig("mygraph.png") 找到下面的工作良好。

    %matplotlib inline
    import sys
    import matplotlib
    
    
    import pandas as pd
    import matplotlib.pyplot as plt
    
    health_data = pd.read_csv("data.csv", header=0, sep=",")
    
    health_data.plot(x ='Average_Pulse', y='Calorie_Burnage', kind='line'),
    plt.ylim(ymin=0, ymax=400)
    plt.xlim(xmin=0, xmax=150)
    
    plt.show()
    
    #Two  lines to make our compiler able to draw:
    plt.savefig("mygraph.png")
    sys.stdout.flush()
    
© www.soinside.com 2019 - 2024. All rights reserved.