すべてのプロットが別の列の値に対応する、列のすべての値に対して異なるバーをプロットする方法は?

Dec 04 2020

以下に示すように、このデータフレームがあります。

data = [['AK','Coal',24457],
['AK','Natural ',222867],
['AK','Other ',15],
['AK','Petro',83848],
['AL','Coal ',169877],
['AL','Natural ',10692],
['AL','Other ',2631],
['AL','Petro',235853]]

df = pd.DataFrame(data, columns = ['STATE','ENERGY','CONSUME']) 

私はそれをグラフにプロットしようとしています。グラフは次の画像のように見える必要があります。

すべてのバーは、それぞれの「ENERGY」の「CONSUME」値に対応します。これは、「STATE」に基づいて値をグループ化し、「ENERGY」に基づいて異なるバーをプロットするようなものです。したがって、基本的に、すべての「STATE」には、4つの異なる「ENERGY」値を示す4つのバーがあります。私はいくつかのことを試みましたが、それらは私が望むようには機能しませんでした。

回答

Pygirl Dec 04 2020 at 15:30

スコットボストンが彼の答えの1つで与えたコードを変更しているだけです。その答えも見てください。

import pandas as pd
import matplotlib.pyplot as plt
from itertools import groupby
import numpy as np 
%matplotlib inline

data = [['AK','Coal',24457],
['AK','Natural ',222867],
['AK','Other ',15],
['AK','Petro',83848],
['AL','Coal ',169877],
['AL','Natural ',10692],
['AL','Other ',2631],
['AL','Petro',235853]]
df = pd.DataFrame(data, columns = ['STATE','ENERGY','CONSUME']) 
df = df.set_index(['STATE','ENERGY', 'STATE'])['CONSUME'].unstack()


def add_line(ax, xpos, ypos):
    line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
                      transform=ax.transAxes, color='gray')
    line.set_clip_on(False)
    ax.add_line(line)

def label_len(my_index,level):
    labels = my_index.get_level_values(level)
    return [(k, sum(1 for i in g)) for k,g in groupby(labels)]

def label_group_bar_table(ax, df):
    ypos = -.1
    scale = 1./df.index.size
    for level in range(df.index.nlevels)[::-1]:
        pos = 0
        for label, rpos in label_len(df.index,level):
            lxpos = (pos + .5 * rpos)*scale
            ax.text(lxpos, ypos, label, ha='center', transform=ax.transAxes)
            add_line(ax, pos*scale, ypos)
            pos += rpos
        add_line(ax, pos*scale , ypos)
        ypos -= .1

ax = df.plot(kind='bar')
#Below 2 lines remove default labels
ax.set_xticklabels('')
ax.set_xlabel('')
label_group_bar_table(ax, df)