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

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

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

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

Python

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

Q&A

解決済

1回答

1320閲覧

二つデータに互換性がない???

Pablito

総合スコア71

Matplotlib

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

Python

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

0グッド

0クリップ

投稿2019/08/16 05:43

前提・実現したいこと

Titanicのデータを使って
データ加工の練習をしています。
そこで生存者と死亡者に分け、
それぞれの年齢をbinで区切ったデータを
matplotlibで描画したいと考えています。

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

ValueError Traceback (most recent call last) <ipython-input-38-71ca1fe4eb72> in <module> 1 plt.figure(figsize = (100, 60)) ----> 2 plt.bar(age, age2, align='center', width = 1.0) 3 plt.xticks(x, ['Surviver', 'Dead']) 4 plt.ylabel('age') 5 plt.grid(True) c:\users\jupyter-notebook\lib\site-packages\matplotlib\pyplot.py in bar(x, height, width, bottom, align, data, **kwargs) 2438 return gca().bar( 2439 x, height, width=width, bottom=bottom, align=align, -> 2440 **({"data": data} if data is not None else {}), **kwargs) 2441 2442 c:\users\jupyter-notebook\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs) 1599 def inner(ax, *args, data=None, **kwargs): 1600 if data is None: -> 1601 return func(ax, *map(sanitize_sequence, args), **kwargs) 1602 1603 bound = new_sig.bind(ax, *args, **kwargs) c:\users\jupyter-notebook\lib\site-packages\matplotlib\axes\_axes.py in bar(self, x, height, width, bottom, align, **kwargs) 2373 x, height, width, y, linewidth = np.broadcast_arrays( 2374 # Make args iterable too. -> 2375 np.atleast_1d(x), height, width, y, linewidth) 2376 2377 # Now that units have been converted, set the tick locations. <__array_function__ internals> in broadcast_arrays(*args, **kwargs) c:\users\jupyter-notebook\lib\site-packages\numpy\lib\stride_tricks.py in broadcast_arrays(*args, **kwargs) 262 args = [np.array(_m, copy=False, subok=subok) for _m in args] 263 --> 264 shape = _broadcast_shape(*args) 265 266 if all(array.shape == shape for array in args): c:\users\jupyter-notebook\lib\site-packages\numpy\lib\stride_tricks.py in _broadcast_shape(*args) 189 # use the old-iterator because np.nditer does not handle size 0 arrays 190 # consistently --> 191 b = np.broadcast(*args[:32]) 192 # unfortunately, it cannot handle 32 or more arguments directly 193 for pos in range(32, len(args), 31): ValueError: shape mismatch: objects cannot be broadcast to a single shape

該当のソースコード

Python

1survivers = data.query("Survived_y == 1") 2dead = data.query("Survived_y == 0") 3bins = [18, 25, 35, 45, 60, 80, 100] 4age = pd.cut(survivers['Age'], bins) 5age2 = pd.cut(dead['Age'], bins) 6 7plt.figure(figsize = (10, 6)) 8plt.bar(age, age2, align='center', width = 0.5) 9plt.xticks(x, ['Surviver', 'Dead']) 10plt.ylabel('age') 11plt.grid(True)

試したこと

エラー的には
plt.bar(age, age2, align='center', width = 1.0)
が違うようなので、この数字をいじってみたりしました。

ただ、調べているとage, age2の形が違い、
互換性がないのが原因のようなのですが、
元々一つのデータだしなーとか思ったりしてます。

ご協力を宜しくお願い致します。

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

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

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

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

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

guest

回答1

0

ベストアンサー

matplotlib.pyplot.bar(x, height, ...)

となっており、x が棒の位置のリスト、height は棒の高さのリストを渡すようになっているので、関数の使い方が間違ってます。

matplotlib.pyplot.bar — Matplotlib 3.1.0 documentation

おそらく、生存者/死亡者ごとに各年例のヒストグラムを描画したいのだと思うので、seaborn の countplot を使うことをおすすめします。

python

1import pandas as pd 2import seaborn as sns 3 4sns.set() 5 6data = pd.read_csv( 7 "https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv" 8) 9 10# 離散値をカテゴリ変数にする。 11data["AgeCat"] = pd.cut(data['Age'], [0, 18, 25, 35, 45, 60, 80, 100]) 12 13# ヒストグラムを描画する。 14sns.countplot(x="AgeCat", hue="Survived", data=data)

イメージ説明

投稿2019/08/16 05:54

tiitoi

総合スコア21956

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

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

Pablito

2019/08/16 06:12

tiitoiさん ご回答ありがとうございます! 頂いた回答を参考にしてみたら ValueError: Could not interpret input 'Survived' が起きました! これの直し方ご教示頂けませんでしょうか?
Pablito

2019/08/16 06:12

sns.set() data["AgeCat"] = pd.cut(data['Age'], [0, 18, 25, 35, 45, 60, 80, 100]) sns.countplot(x="AgeCat", hue="Survived", data=data)
Pablito

2019/08/16 06:13

gender = pd.read_csv(r'G:\マイドライブ\Data processing\gender_submission.csv', engine='python', dtype={'PassengerId': object}) test = pd.read_csv(r'G:\マイドライブ\Data processing\test.csv', engine='python', dtype={'PassengerId': object}) train = pd.read_csv(r'G:\マイドライブ\Data processing\train.csv', engine='python', dtype={'PassengerId': object}) dataset = pd.merge(test, train, how='outer') data = pd.merge(dataset, gender, on='PassengerId')
tiitoi

2019/08/16 06:15

お使いの taitanic のデータはどこから取得したものでしょうか? 列名がこちらで使用したファイルと微妙に違うのだと思います。 生存しているかどうかが記載された列があると思うので、hue にはその列名を記載してください。
Pablito

2019/08/16 06:19

データはhttps://www.kaggle.com/c/titanic/data から入手致しました! hueの件、承知いたしました。 試してみます!!!
Pablito

2019/08/16 06:20

ありがとうございます! シンプルにhueを変えたらできました! ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問