1980年,1990年,2000年,2010年,2020年の平均気温変化をグラフで表したい
こんにちは。
気象動向をスクレイピングで調査しており、10年ごとの月別平均気温の変化をグラフで可視化しようとしております。
皆様の協力あってスクレイピング自体はうまくいったのですが、1990年以降のグラフをうまく可視化することができないという問題に直面しました。X軸の設定は調整できているのですが、Y軸の設定がうまくいきません。逆にY軸をいじろうとすると、かえってX軸の範囲がおかしくなってしまい、どのように対処すればよいのかお伺いできればと思います。
グラフの作り方もまだ勉強中ですので、もっとシンプルな方法がある、このライブラリを使うべき、などのご意見がありましたら、是非参考にさせて頂きます。
よろしくお願いいたします。
コード、CSVはgithubの方にもアップロードしておきます。(追記:URLの間違いを訂正)
https://github.com/yamaplay/Weather_scr_avg
2000年のグラフが歪んでしまう
まず正しいグラフがどのようなものかが把握できないと思いますので、エクセルで作成した2000年のグラフをご覧ください。
下記のコードを実行すると、このようなグラフになってしまいます。原因ですが、おそらく私がコードや範囲指定を誤っているせいだと思います。
ソースコード
import requests from bs4 import BeautifulSoup import csv place_name = ["札幌", "秋田", "新潟", "東京", "大阪", "広島", "高知", "熊本", "那覇"] place_codeA = [14, 32, 54, 44, 62, 67, 74, 86, 91] place_codeB = [47412, 47582, 47604, 47662, 47772, 47765, 47893, 47819, 47936] base_url = "http://www.data.jma.go.jp/obd/stats/etrn/view/monthly_s1.php?prec_no=%s&block_no=%s&year=%s&month=1&day=1&view=p1" def str2float(str): try: return float(str) except: return 0.0 if __name__ == "__main__": for place in place_name: All_list = [['年月', '降水量(mm)', '日の平均気温(℃)', '日の最高気温(℃)', '日の最低気温(℃)', '最高気温(℃)', '最低気温(℃)']] print(place) index = place_name.index(place) for year in range(1980, 2021): print(year) r = requests.get(base_url%(place_codeA[index], place_codeB[index], year)) r.encoding = r.apparent_encoding soup = BeautifulSoup(r.text) rows = soup.findAll('tr',class_='mtx') rows = rows[3:] for row in rows: data = row.findAll('td') rowData = [] #初期化 rowData.append(str(year) + "/" + str(data[0].string)) rowData.append(str2float(data[3].string)) rowData.append(str2float(data[7].string)) rowData.append(str2float(data[8].string)) rowData.append(str2float(data[9].string)) rowData.append(str2float(data[10].string)) rowData.append(str2float(data[11].string)) All_list.append(rowData) with open(place + '.csv', 'w') as file: writer = csv.writer(file, lineterminator='\n') writer.writerows(All_list) import matplotlib.pylab as plt import pandas as pd df=pd.read_csv('熊本.csv', encoding="SHIFT_JIS") h1, =plt.plot(df['日の平均気温(℃)'][0:12],label='1980/1~1980/12') plt.xticks(range(12),df['年月'][0:12],rotation=90,size='small') plt.legend(handles=[h1]) plt.show()#1980年のものはきれいに出力される df=pd.read_csv('熊本.csv', encoding="SHIFT_JIS") h2, =plt.plot(df['日の平均気温(℃)'][240:252],label='2000/1~2000/12') plt.xticks(range(12),df['年月'][240:252],rotation=90,size='small') plt.legend(handles=[h2]) plt.show()#こちらはグラフ自体は正しく出ているが、うまく描画できていない。 df=pd.read_csv('熊本.csv', encoding="SHIFT_JIS") h2, =plt.plot(df['日の平均気温(℃)'][0:12],label='2000/1~2000/12') plt.xticks(range(12),df['年月'][240:252],rotation=90,size='small') plt.legend(handles=[h2]) plt.show()#グラフは当然1980年のものになってしまう
補足、参考
参考にしているサイトは以下の通りです。
Pythonの覚え書き(グラフのプロット編)
https://hirotaka-hachiya.hatenablog.com/entry/2015/12/29/123142

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/03/06 07:44