【Python】for文を活用して一つのグラフ内に、複数の折れ線グラフをいれる方法をご教示ください!
■使用言語とライブラリ
・Python
・Google Colaboratory
■本文
現在スポーツジムにて、ユーザーの会員区分別で店舗毎(shop_name)のユーザー数の推移を
matplotlibのplotとfor文を使って、一つのグラフの中にまとめたいと考えております。
こちらに当たって、以下エラーが発生しており、困っております。
※実施手順
0.元データをshop_userという変数にいれたとします。
↓↓イメージ
1.元データをフィルタで抽出(今回はナイトタイム会員を例にしてます)
shop_user = shop_user.loc[shop_user["user_type"] == "ナイト会員"]
shop_user
2.ショップ毎のユーザー推移(月日であるmeasurement_monthごと)をユーザーIDから算出
shop_nightuser_uupivot = shop_user.pivot_table(index = "measurement_month", columns = "store_name", values = "user_id", aggfunc = "count", fill_value = 0)
shop_nightuser_uupivot
3.横軸をmeasurement_month、縦軸を各store_nameにした折れ線グラフを記載(一つのグラフ内にまとめる)
for i in list(shop_nightuser_uupivot):
plt.plot(shop_nightuser_uupivot["measurement_month"], shop_nightuser_uupivot[i])
plt.legend()
plt.show()
※ここで以下のようなエラーが発生します。
KeyError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3360 try:
-> 3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
4 frames
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'measurement_month'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3361 return self._engine.get_loc(casted_key)
3362 except KeyError as err:
-> 3363 raise KeyError(key) from err
3364
3365 if is_scalar(key) and isna(key) and not self.hasnans:
KeyError: 'measurement_month'
measurement_monthのKeyErrorとなっておりますが、
measurement_monthはデータフレームを表示しても入っているため、
何が要因でエラーが起きているかが理解できておらず、
こちらなにかおわかりになる方がいらっしゃれば、
ご教示いただけますと幸いです。
※またコードや考え方がそもそも間違っているなども、ご指摘いただけますと幸いです。
恐れ入りますが、よろしくお願いいたします。
0 likes