質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

4049閲覧

matplotlibで凡例を一つにまとめたい

kouheichild

総合スコア18

Matplotlib

MatplotlibはPythonのおよび、NumPy用のグラフ描画ライブラリです。多くの場合、IPythonと連携して使われます。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2018/09/25 08:24

前提・実現したいこと

Python初心者です.
あるデータからグラフを描画しています.
6つのグラフの凡例を一つにまとめたいのですが,どのようにすればよいのでしょうか.
以下のエラーメッセージが発生しました。
jupyter notebookで行っています.
どなたかご教授いただけたら幸いです.

発生している問題・エラーメッセージ

--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-154-cab28147f5ab> in <module>() 66 p = [p1, p2, p3, p4 ,p5, p6] 67 ---> 68 ax1.legend(p, [i.get_label() for i in p], loc='center right', borderaxespad=0.5, fontsize=16, frameon=False) 69 70 R2_car = r2_score(y_car, y_car_pred) <ipython-input-154-cab28147f5ab> in <listcomp>(.0) 66 p = [p1, p2, p3, p4 ,p5, p6] 67 ---> 68 ax1.legend(p, [i.get_label() for i in p], loc='center right', borderaxespad=0.5, fontsize=16, frameon=False) 69 70 R2_car = r2_score(y_car, y_car_pred) AttributeError: 'list' object has no attribute 'get_label'

該当のソースコード

Python

1%matplotlib inline 2import numpy as np 3import pandas as pd 4import matplotlib.pyplot as plt 5import seaborn as sns 6from scipy import stats 7from scipy.optimize import curve_fit 8from sklearn.metrics import r2_score 9 10# データ 11 12x = np.array([ 4., 9., 14., 19., 24., 29., 34., 39., 44., 13 49., 54., 59., 64., 69., 74., 79., 84., 89., 14 94., 99., 104., 109., 114., 119., 124., 129., 134., 15 139., 144., 149., 154., 159., 164.]) 16 17car = np.array([400, 340, 585, 140, 250, 210, 195, 55, 145, 30, 50, 35, 35, 18 5, 35, 2, 2, 2, 4, 0, 15, 2, 0, 2, 2, 0, 19 10, 0, 0, 0, 2, 0, 0]) 20 21ped = np.array([520, 340, 645, 160, 290, 240, 315, 125, 155, 20, 50, 25, 45, 22 5, 15, 0, 8, 13, 6, 0, 5, 0, 10, 0, 0, 0, 23 0, 0, 0, 5, 8, 0, 0]) 24 25y_car = np.array([ 0.15667842, 0.28985507, 0.51899726, 0.5738347 , 0.67175872, 26 0.75401488, 0.83039561, 0.8519389 , 0.90873482, 0.9204857 , 27 0.94007051, 0.95377987, 0.96748923, 0.96944771, 0.98315707, 28 0.98394046, 0.98472385, 0.98550725, 0.98707403, 0.98707403, 29 0.99294947, 0.99373286, 0.99373286, 0.99451626, 0.99529965, 30 0.99529965, 0.99921661, 0.99921661, 0.99921661, 0.99921661, 31 1. , 1. , 1. ]) 32y_ped = np.array([ 0.17304493, 0.28618968, 0.50083195, 0.55407654, 0.65058236, 33 0.73044925, 0.83527454, 0.87687188, 0.92845258, 0.93510815, 34 0.95174709, 0.96006656, 0.9750416 , 0.97670549, 0.98169717, 35 0.98169717, 0.9843594 , 0.98868552, 0.9906822 , 0.9906822 , 36 0.99234609, 0.99234609, 0.99567388, 0.99567388, 0.99567388, 37 0.99567388, 0.99567388, 0.99567388, 0.99567388, 0.99733777, 38 1. , 1. , 1. ]) 39 40# 近似線と決定係数 41def cdf_car(x, a, b, c): 42 return stats.lognorm.cdf(x, a, b, c) 43param, cov = curve_fit(cdf_car, x, y_car) 44def cdf_ped(x, a, b, c): 45 return stats.lognorm.cdf(x, a, b, c) 46param, cov = curve_fit(cdf_ped, x, y_ped) 47 48y_car_pred = cdf_car(x, *param) 49y_ped_pred = cdf_ped(x, *param) 50 51R2_car = r2_score(y_car, y_car_pred) 52R2_ped = r2_score(y_ped, y_ped_pred) 53 54# 描画 55fig, ax1 = plt.subplots() 56ax2 = ax1.twinx() 57 58w = 2 59p1 = ax1.bar(x + w/2, car, label = 'car', alpha = 0.5, color = 'blue', align = 'center', width = w) 60p2 = ax1.bar(x - w/2, ped, label = 'pedestrian', alpha = 0.5, color = 'green', align = 'center', width = w) 61 62p3 = ax2.scatter(x , y_car, label = 'car accumulation', marker = 'o', color = 'blue', facecolors = 'none', edgecolor = 'blue', linewidth = 1.5 ) 63p4 = ax2.scatter(x , y_ped, label = 'ped accumulation', marker = 'o', facecolors = 'none', color = 'green', edgecolor = 'green', linewidth = 1.5 ) 64 65p5 = ax2.plot(x, y_car_pred, linestyle="--", label="car fitting", color = 'blue', alpha = 0.7) 66p6 = ax2.plot(x, y_ped_pred, linestyle="--", label="ped fitting", color = 'green' , alpha = 0.7) 67 68ax1.set_xlabel('start time(min)') 69ax1.set_ylabel('number of people') 70ax2.set_ylabel('F(x)') 71 72p = [p1, p2, p3, p4 ,p5, p6] 73ax1.legend(p, [i.get_label() for i in p]) 74

試したこと

p = [p1, p2, p3, p4 ]とすると凡例が一つに表示されます.
おそらくp5, p6 で問題があるのだと推測しました.

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

plot()にはxとyに2次元配列を渡して複数の線を引く機能があります。そのため、返り値はLine2D objectsのリストになります。

matplotlib.axes.Axes.plot — Matplotlib 3.0.0 documentation

今回は要素数1のリストになっているので、そのまま取り出せば大丈夫です。

あと、近似の部分がうまくいっていなかったので直してみました。

python

1import numpy as np 2import pandas as pd 3import matplotlib.pyplot as plt 4import seaborn as sns 5from scipy import stats 6from scipy.optimize import curve_fit 7from sklearn.metrics import r2_score 8 9# データ 10 11x = np.array([ 4., 9., 14., 19., 24., 29., 34., 39., 44., 12 49., 54., 59., 64., 69., 74., 79., 84., 89., 13 94., 99., 104., 109., 114., 119., 124., 129., 134., 14 139., 144., 149., 154., 159., 164.]) 15 16car = np.array([400, 340, 585, 140, 250, 210, 195, 55, 145, 30, 50, 35, 35, 17 5, 35, 2, 2, 2, 4, 0, 15, 2, 0, 2, 2, 0, 18 10, 0, 0, 0, 2, 0, 0]) 19 20ped = np.array([520, 340, 645, 160, 290, 240, 315, 125, 155, 20, 50, 25, 45, 21 5, 15, 0, 8, 13, 6, 0, 5, 0, 10, 0, 0, 0, 22 0, 0, 0, 5, 8, 0, 0]) 23 24y_car = np.array([ 0.15667842, 0.28985507, 0.51899726, 0.5738347 , 0.67175872, 25 0.75401488, 0.83039561, 0.8519389 , 0.90873482, 0.9204857 , 26 0.94007051, 0.95377987, 0.96748923, 0.96944771, 0.98315707, 27 0.98394046, 0.98472385, 0.98550725, 0.98707403, 0.98707403, 28 0.99294947, 0.99373286, 0.99373286, 0.99451626, 0.99529965, 29 0.99529965, 0.99921661, 0.99921661, 0.99921661, 0.99921661, 30 1. , 1. , 1. ]) 31y_ped = np.array([ 0.17304493, 0.28618968, 0.50083195, 0.55407654, 0.65058236, 32 0.73044925, 0.83527454, 0.87687188, 0.92845258, 0.93510815, 33 0.95174709, 0.96006656, 0.9750416 , 0.97670549, 0.98169717, 34 0.98169717, 0.9843594 , 0.98868552, 0.9906822 , 0.9906822 , 35 0.99234609, 0.99234609, 0.99567388, 0.99567388, 0.99567388, 36 0.99567388, 0.99567388, 0.99567388, 0.99567388, 0.99733777, 37 1. , 1. , 1. ]) 38 39# 近似線と決定係数 40def cdf(x, a, b, c): 41 return stats.lognorm.cdf(x, a, b, c) 42car_param, car_cov = curve_fit(cdf, x, y_car) # パラメータをそれぞれで分けないといけない。関数は分けなくて良い。covは使わないが一応分けておく 43ped_param, ped_cov = curve_fit(cdf, x, y_ped) 44 45y_car_pred = cdf(x, *car_param) 46y_ped_pred = cdf(x, *ped_param) 47 48R2_car = r2_score(y_car, y_car_pred) 49R2_ped = r2_score(y_ped, y_ped_pred) 50 51# 描画 52fig, ax1 = plt.subplots() 53ax2 = ax1.twinx() 54 55w = 2 56p1 = ax1.bar(x + w/2, car, label = 'car', alpha = 0.5, color = 'blue', align = 'center', width = w) 57p2 = ax1.bar(x - w/2, ped, label = 'pedestrian', alpha = 0.5, color = 'green', align = 'center', width = w) 58 59p3 = ax2.scatter(x , y_car, label = 'car accumulation', marker = 'o', color = 'blue', facecolors = 'none', edgecolor = 'blue', linewidth = 1.5 ) 60p4 = ax2.scatter(x , y_ped, label = 'ped accumulation', marker = 'o', facecolors = 'none', color = 'green', edgecolor = 'green', linewidth = 1.5 ) 61 62p5 = ax2.plot(x, y_car_pred, linestyle="--", label="car fitting", color = 'blue', alpha = 0.7) 63p6 = ax2.plot(x, y_ped_pred, linestyle="--", label="ped fitting", color = 'green' , alpha = 0.7) 64 65ax1.set_xlabel('start time(min)') 66ax1.set_ylabel('number of people') 67ax2.set_ylabel('F(x)') 68 69p = [p1, p2, p3, p4, p5[0], p6[0]] 70ax1.legend(p, [i.get_label() for i in p]) 71plt.show() 72

投稿2018/09/25 08:38

編集2018/09/25 09:09
hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kouheichild

2018/09/25 09:16

hayataka2049様 回答していただきましてありがとうございます. plot()に関してよく理解していませんでした.よく勉強させていただきます. また,先日お答えしていただいた近似線に関しても,直していただきましてありがとうございます.小生に理解力がないため,二度もお手を煩わせてしまってすみません. ありがとうございました.
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問