2017-03-14 3 views
0

편집 2017년 3월 15일 중부 서머 타임 오후 12시는 : 나는 프로그램의 오류를 수정하고 설계되었을 때 프로그램을 완료하는 데 성공했다. Berna1111과 TigerhawkT3에 감사의 말을 전하며,이 프로그램을 완료 할 수있었습니다. 다시 한 번 감사드립니다. Stack Overflow!왜 "AttributeError : 'tuple'객체에 'savefig'속성이 없습니까?


내가 배열 내장 히스토그램 형 .png 파일을 (NumPy와 및하기 matplotlib를 사용하여 막대 그래프로 만든 배열)의 시리즈를 저장하려고하고 있습니다.

figure1 = plt.hist(temperature_graph_array, color="blue") 
figure2 = plt.hist(feelslike_graph_array, color="blue") 
figure3 = plt.hist(windspeed_graph_array, color="blue") 
figure4 = plt.hist(windgustspeed_graph_array, color="blue") 
figure5 = plt.hist(pressure_graph_array, color="blue") 
figure6 = plt.hist(humidity_graph_array, color="blue") 

figure1.savefig("{}_temperature.png".format(filename), format='png') 
figure2.savefig("{}_feelslike.png".format(filename), format='png') 
figure3.savefig("{}_windspeed.png".format(filename), format='png') 
figure4.savefig("{}_windgustspeed.png".format(filename), format='png') 
figure5.savefig("{}_pressure.png".format(filename), format='png') 
figure6.savefig("{}_humidity.png".format(filename), format='png') 

가 왜이 오류가 발생하고, 어떻게 고칠 수 있습니다

Traceback (most recent call last): 
    File "C:/Users/Ryan/PycharmProjects/NWS/weather_data.py", line 475, in <module> 
    figure1.savefig("{}_temperature.png".format(filename)) 
AttributeError: 'tuple' object has no attribute 'savefig' 

오류가 참조 섹션은 다음과 같습니다 : 나는 다음과 같은 오류 메시지가 무엇입니까? 누군가가 내게 알려 주면 크게 감사 할 것입니다.


참고 :

  • 내가 검색 좀 구글에서 일을 발견 몇 가지 유사한 오류를, 그러나 아무도 그림은 튜플로 해석 된 곳있다. 튜플 부분이 어디에서 왔는지 이해할 수 없습니다.

  • 히스토그램 작성 단계의 "_graph_array"항목은 길이 10, 길이가 1 인 차원의 배열입니다. 내부에 총 10 개의 항목이 있으며 플로트 유형으로 지정됩니다.

  • 저장 단계의 "filename"변수는 날짜와 시간이 포함 된 문자열을 나타냅니다. documentation for matplotlib.pyplot.hist에서


+0

'plt.hist' 당신은 그림을 작성해야하는'figure' instace을 반환하지 않습니다 (', 필립스 = PLT :

더 나은, 당신은 당신의 데이터에 모든 것을 할 수있는 기능을 사용할 수 있습니다 .(ax1 = fig1.add_subplots (111)') 축에 그립니다 ('ax1.hist (...)'). 이 시점에서 그림을 저장할 수 있어야합니다 ('fig1.savefig (...)'). 테스트 후 답변을 게시합니다. – berna1111

+0

수정 : ax1 = fig1.add_subplot' * s *'(111)'이 아닌'ax1 = fig1.add_subplot (111)'! – berna1111

답변

2

난 당신의 코드를 적응 for 루프의 이해에 목록으로 그림을 만드는 여러 줄을 변경할 수있는 자유 갔다했습니다

이 가 이

는, 결과 수치를 게시하지만하지 않음이 제공

import matplotlib.pyplot as plt 
# should be equal when using .pylab 
import numpy.random as rnd 

# generate_data 
n_points = 1000 
temperature_graph_array = rnd.random(n_points) 
feelslike_graph_array = rnd.random(n_points) 
windspeed_graph_array = rnd.random(n_points) 
windgustspeed_graph_array = rnd.random(n_points) 
pressure_graph_array = rnd.random(n_points) 
humidity_graph_array = rnd.random(n_points) 
list_of_data = [temperature_graph_array, 
       feelslike_graph_array, 
       windspeed_graph_array, 
       windgustspeed_graph_array, 
       pressure_graph_array, 
       humidity_graph_array] 
list_of_names = ['temperature', 
       'feelslike', 
       'windspeed', 
       'windgustspeed', 
       'pressure', 
       'humidity'] 

# create the figures: 
#figure1 = plt.figure() 
#figure2 = plt.figure() 
#figure3 = plt.figure() 
#figure4 = plt.figure() 
#figure5 = plt.figure() 
#figure6 = plt.figure() 
#list_of_figs = [figure1, figure2, figure3, figure4, figure5, figure6] 
## could be: 
list_of_figs = [plt.figure() for i in range(6)] 

# create the axis: 
#ax1 = figure1.add_subplot(111) 
#ax2 = figure2.add_subplot(111) 
#ax3 = figure3.add_subplot(111) 
#ax4 = figure4.add_subplot(111) 
#ax5 = figure5.add_subplot(111) 
#ax6 = figure6.add_subplot(111) 
#list_of_axis = [ax1, ax2, ax3, ax4, ax5, ax6] 
## could be: 
list_of_axis = [fig.add_subplot(111) for fig in list_of_figs] 

# plot the histograms 
# notice `plt.hist` returns a tuple (n, bins, patches) or 
# ([n0, n1, ...], bins, [patches0, patches1,...]) if the input 
# contains multiple data 
#hist1 = ax1.hist(temperature_graph_array, color="blue") 
#hist2 = ax2.hist(feelslike_graph_array, color="blue") 
#hist3 = ax3.hist(windspeed_graph_array, color="blue") 
#hist4 = ax4.hist(windgustspeed_graph_array, color="blue") 
#hist5 = ax5.hist(pressure_graph_array, color="blue") 
#hist6 = ax6.hist(humidity_graph_array, color="blue") 
#list_of_hists = [hist1, hist2, hist3, hist4, hist5, hist6] 
## could be: 
list_of_hists = [] 
for i, ax in enumerate(list_of_axis): 
    list_of_hists.append(ax.hist(list_of_data[i], color="blue")) 

filename = 'output_graph' 
for i, fig in enumerate(list_of_figs): 
    name = list_of_names[i].capitalize() 
    list_of_axis[i].set_title(name) 
    fig.tight_layout() 
    fig.savefig("{}_{}.png".format(filename,name), format='png') 
을 스크립트와 같은 폴더에 6 개의 작은 .png 파일이 있습니다.

def save_hist(data, name, filename): 
    fig = plt.figure() 
    ax = fig.add_subplot(111) 
    ax.hist(data, color="blue") 
    ax.set_title(name) 
    fig.tight_layout() 
    fig.savefig("{}_{}.png".format(filename,name), format='png') 
    plt.close(fig) 

filename = 'output_graph_2' 
for data, name in zip(list_of_data, list_of_names): 
    save_hist(data, name, filename) 
+0

좋은데, 도와 줘서 고마워! –

3

:

The return value is a tuple (n , bins , patches) or ([ n0 , n1 , ...], bins , [ patches0 , patches1 ,...]) if the input contains multiple data.

documentation for matplotlib.pyplot.savefig에서 : 당신이에없는, 당신은 hist 전화를 같은 방법으로 savefig를 호출해야합니다 같은

Save the current figure.

같습니다 hist 호출 결과

plt.savefig("{}_temperature.png".format(filename), format='png') 
... 
+0

답변 해 주셔서 감사합니다. 그러나 작동하지 않습니다. "hist"함수를 실행할 때, 실제로 그 단계는 그래프를 생성합니다. 그래프를 만들지 않으면 저장할 그래프가 없습니다. 귀하의 솔루션은 단순히 그래프 생성을 제거합니다. –

+0

@RyanWitek - 네,'hist()'와'savefig()'를 호출해야하지만'savefig'는'matplotlib.pyplot'의 메소드입니다. hist()가 반환하는 메소드가 아닙니다 (a 튜플). – TigerhawkT3

관련 문제