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

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

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

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

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

Q&A

解決済

1回答

827閲覧

pandasのdataframe.plot.barとdataframe.plot(kind=bar)の違い

Kumazaemon

総合スコア5

Python

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

pandas

Pandasは、PythonでRにおけるデータフレームに似た型を持たせることができるライブラリです。 行列計算の負担が大幅に軽減されるため、Rで行っていた集計作業をPythonでも比較的簡単に行えます。 データ構造を変更したりデータ分析したりするときにも便利です。

0グッド

0クリップ

投稿2021/01/03 00:36

初心者です。
python3で、pandasを使ってデータフレームの可視化(業務書類に使用したいので、最終的にはかなり調整をして完成されたレイアウトにしていきたい)の勉強中です。

調べてみると、例えば棒グラフを書くときに、
df.plot.bar(stacked=1)
のようにも、
df.plot(kind=bar, stacked=1)
のようにも書けるようです。

やってみると見た目はまったく同じものができましたが、これはどういう違いがあるのでしょうか。
例えば、引数の一番最初のものに特権があってカッコの外に出せるという暗黙のルールがあるとか、別のメソッドで実は似ているけど違うコードで作られたグラフで用途により使いわけたほうがよいとか、そういうことをお尋ねしたいです。

宜しくお願いします。

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

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

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

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

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

guest

回答1

0

ベストアンサー

「引数の一番最初のものに特権があってカッコの外に出せるという暗黙のルール」はありません。
使ったことがないので詳しくはわかりませんが、df.plotでキーワード引数kind=barが指定されたときにはdf.plot.barを呼び出すように実装されている可能性が高いです。
kindに他のもの(histとかboxとか)を指定したときも同様です。

調べてみたところ、大本はpd.plotting._core.PlotAccessor.barのようです。df.plotでキーワード引数kind=barが指定されたときもdf.plot.barも、pd.plotting._core.PlotAccessor.barに帰着するので同じ動きをするということです。なぜそうなるかというと、pandasの作成者がそう作ったからであるとしか言いようがなく、一般的にどうこういえるものではありません。

それぞれの説明を見たければhelp(df.plot)とか、print(df.plot.doc)とかをやってみてください。
以下の様な説明が出ます。(英語を読むのが大変かもしれませんが)

python

1>>> print(df.plot.__doc__) 2 3 Make plots of Series or DataFrame. 4 5 Uses the backend specified by the 6 option ``plotting.backend``. By default, matplotlib is used. 7 8 Parameters 9 ---------- 10 data : Series or DataFrame 11 The object for which the method is called. 12 x : label or position, default None 13 Only used if data is a DataFrame. 14 y : label, position or list of label, positions, default None 15 Allows plotting of one column versus another. Only used if data is a 16 DataFrame. 17 kind : str 18 The kind of plot to produce: 19 20 - 'line' : line plot (default) 21 - 'bar' : vertical bar plot 22 - 'barh' : horizontal bar plot 23 - 'hist' : histogram 24 - 'box' : boxplot 25 - 'kde' : Kernel Density Estimation plot 26 - 'density' : same as 'kde' 27 - 'area' : area plot 28 - 'pie' : pie plot 29 - 'scatter' : scatter plot 30 - 'hexbin' : hexbin plot. 31 32 figsize : a tuple (width, height) in inches 33 use_index : bool, default True 34 Use index as ticks for x axis. 35 title : str or list 36 Title to use for the plot. If a string is passed, print the string 37 at the top of the figure. If a list is passed and `subplots` is 38 True, print each item in the list above the corresponding subplot. 39 grid : bool, default None (matlab style default) 40 Axis grid lines. 41 legend : bool or {'reverse'} 42 Place legend on axis subplots. 43 style : list or dict 44 The matplotlib line style per column. 45 logx : bool or 'sym', default False 46 Use log scaling or symlog scaling on x axis. 47 .. versionchanged:: 0.25.0 48 49 logy : bool or 'sym' default False 50 Use log scaling or symlog scaling on y axis. 51 .. versionchanged:: 0.25.0 52 53 loglog : bool or 'sym', default False 54 Use log scaling or symlog scaling on both x and y axes. 55 .. versionchanged:: 0.25.0 56 57 xticks : sequence 58 Values to use for the xticks. 59 yticks : sequence 60 Values to use for the yticks. 61 xlim : 2-tuple/list 62 ylim : 2-tuple/list 63 rot : int, default None 64 Rotation for ticks (xticks for vertical, yticks for horizontal 65 plots). 66 fontsize : int, default None 67 Font size for xticks and yticks. 68 colormap : str or matplotlib colormap object, default None 69 Colormap to select colors from. If string, load colormap with that 70 name from matplotlib. 71 colorbar : bool, optional 72 If True, plot colorbar (only relevant for 'scatter' and 'hexbin' 73 plots). 74 position : float 75 Specify relative alignments for bar plot layout. 76 From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 77 (center). 78 table : bool, Series or DataFrame, default False 79 If True, draw a table using the data in the DataFrame and the data 80 will be transposed to meet matplotlib's default layout. 81 If a Series or DataFrame is passed, use passed data to draw a 82 table. 83 yerr : DataFrame, Series, array-like, dict and str 84 See :ref:`Plotting with Error Bars <visualization.errorbars>` for 85 detail. 86 xerr : DataFrame, Series, array-like, dict and str 87 Equivalent to yerr. 88 mark_right : bool, default True 89 When using a secondary_y axis, automatically mark the column 90 labels with "(right)" in the legend. 91 include_bool : bool, default is False 92 If True, boolean values can be plotted. 93 backend : str, default None 94 Backend to use instead of the backend specified in the option 95 ``plotting.backend``. For instance, 'matplotlib'. Alternatively, to 96 specify the ``plotting.backend`` for the whole session, set 97 ``pd.options.plotting.backend``. 98 99 .. versionadded:: 1.0.0 100 101 **kwargs 102 Options to pass to matplotlib plotting method. 103 104 Returns 105 ------- 106 :class:`matplotlib.axes.Axes` or numpy.ndarray of them 107 If the backend is not the default matplotlib one, the return value 108 will be the object returned by the backend. 109 110 Notes 111 ----- 112 - See matplotlib documentation online for more on this subject 113 - If `kind` = 'bar' or 'barh', you can specify relative alignments 114 for bar plot layout by `position` keyword. 115 From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 116 (center)

python

1>>> print(df.plot.bar.__doc__) 2 3 Vertical bar plot. 4 5 A bar plot is a plot that presents categorical data with 6 rectangular bars with lengths proportional to the values that they 7 represent. A bar plot shows comparisons among discrete categories. One 8 axis of the plot shows the specific categories being compared, and the 9 other axis represents a measured value. 10 11 Parameters 12 ---------- 13 x : label or position, optional 14 Allows plotting of one column versus another. If not specified, 15 the index of the DataFrame is used. 16 y : label or position, optional 17 Allows plotting of one column versus another. If not specified, 18 all numerical columns are used. 19 **kwargs 20 Additional keyword arguments are documented in 21 :meth:`DataFrame.plot`. 22 23 Returns 24 ------- 25 matplotlib.axes.Axes or np.ndarray of them 26 An ndarray is returned with one :class:`matplotlib.axes.Axes` 27 per column when ``subplots=True``. 28 29 See Also 30 -------- 31 DataFrame.plot.barh : Horizontal bar plot. 32 DataFrame.plot : Make plots of a DataFrame. 33 matplotlib.pyplot.bar : Make a bar plot with matplotlib. 34 35 Examples 36 -------- 37 Basic plot. 38 39 .. plot:: 40 :context: close-figs 41 42 >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]}) 43 >>> ax = df.plot.bar(x='lab', y='val', rot=0) 44 45 Plot a whole dataframe to a bar plot. Each column is assigned a 46 distinct color, and each row is nested in a group along the 47 horizontal axis. 48 49 .. plot:: 50 :context: close-figs 51 52 >>> speed = [0.1, 17.5, 40, 48, 52, 69, 88] 53 >>> lifespan = [2, 8, 70, 1.5, 25, 12, 28] 54 >>> index = ['snail', 'pig', 'elephant', 55 ... 'rabbit', 'giraffe', 'coyote', 'horse'] 56 >>> df = pd.DataFrame({'speed': speed, 57 ... 'lifespan': lifespan}, index=index) 58 >>> ax = df.plot.bar(rot=0) 59 60 Instead of nesting, the figure can be split by column with 61 ``subplots=True``. In this case, a :class:`numpy.ndarray` of 62 :class:`matplotlib.axes.Axes` are returned. 63 64 .. plot:: 65 :context: close-figs 66 67 >>> axes = df.plot.bar(rot=0, subplots=True) 68 >>> axes[1].legend(loc=2) # doctest: +SKIP 69 70 Plot a single column. 71 72 .. plot:: 73 :context: close-figs 74 75 >>> ax = df.plot.bar(y='speed', rot=0) 76 77 Plot only selected categories for the DataFrame. 78 79 .. plot:: 80 :context: close-figs 81 82 >>> ax = df.plot.bar(x='lifespan', rot=0)

投稿2021/01/03 01:47

編集2021/01/03 03:32
ppaul

総合スコア24666

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

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

ppaul

2021/01/03 03:35

pandasのソースを調査して、回答に追加の説明を入れました。 調べ方などはあまり気にしないでください。書きすぎてしまったとも思いますが、さらに経験を積んだときに思い出していただければと考えています。
Kumazaemon

2021/01/03 04:03

ありがとうございます! まさに期待していたアドバイスでした。 同じコード帰着すると分かり、とてもスッキリしました。 (ググって出てきた異なる書き方の例を、同じものだと割り切れるのは初心者にとって精神的にありがたい情報です) helpの使い方も教えてくださり、ありがとうございました!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問