2017-04-21 18 views
14

次のコードは、x軸のラベルとしてメインカテゴリ['one'、 'two'、 'three'、 'four'、 'five'、 'six']のみを示しています。セカンダリx軸ラベルとしてサブカテゴリ['A'、 'B'、 'C​​'、 'D']を表示する方法はありますか?ここで enter image description here複数のラベルを含む棒グラフ

df = pd.DataFrame(np.random.rand(6, 4), 
       index=['one', 'two', 'three', 'four', 'five', 'six'], 
       columns=pd.Index(['A', 'B', 'C', 'D'], 
       name='Genus')).round(2) 


df.plot(kind='bar',figsize=(10,4)) 
+0

私は2つのオプションを考えることができます。1.主1(参照[この](http://stackoverflow.com/questions/31803817以下アドホック二x軸を作成します。/how-to-add-second-x-axis-at-the-first-one-in-matplotlib)); 2. 'df.unstack()。plot.bar()'で始まり、後でFigureの属性を変更します。 – VinceP

答えて

7

可能な解決策(私は楽しみのかなり多くを持っていた!):

df = pd.DataFrame(np.random.rand(6, 4), 
       index=['one', 'two', 'three', 'four', 'five', 'six'], 
       columns=pd.Index(['A', 'B', 'C', 'D'], 
       name='Genus')).round(2) 

ax = df.plot(kind='bar',figsize=(10,4), rot = 0) 

# "Activate" minor ticks 
ax.minorticks_on() 

# Get location of the center of each rectangle 
rects_locs = map(lambda x: x.get_x() +x.get_width()/2., ax.patches) 
# Set minor ticks there 
ax.set_xticks(rects_locs, minor = True) 


# Labels for the rectangles 
new_ticks = reduce(lambda x, y: x + y, map(lambda x: [x] * df.shape[0], df.columns.tolist())) 
# Set the labels 
from matplotlib import ticker 
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(new_ticks)) #add the custom ticks 

# Move the category label further from x-axis 
ax.tick_params(axis='x', which='major', pad=15) 

# Remove minor ticks where not necessary 
ax.tick_params(axis='x',which='both', top='off') 
ax.tick_params(axis='y',which='both', left='off', right = 'off') 

は、ここで私は何を得るのです。ここで

enter image description here

8

は、ソリューションです。あなたはバーの位置を取得し、それに応じていくつかのマイナーxticklabelsを設定することができます。

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 

df = pd.DataFrame(np.random.rand(6, 4), 
       index=['one', 'two', 'three', 'four', 'five', 'six'], 
       columns=pd.Index(['A', 'B', 'C', 'D'], 
       name='Genus')).round(2) 


df.plot(kind='bar',figsize=(10,4)) 

ax = plt.gca() 
pos = [] 
for bar in ax.patches: 
    pos.append(bar.get_x()+bar.get_width()/2.) 


ax.set_xticks(pos,minor=True) 
lab = [] 
for i in range(len(pos)): 
    l = df.columns.values[i//len(df.index.values)] 
    lab.append(l) 

ax.set_xticklabels(lab,minor=True) 
ax.tick_params(axis='x', which='major', pad=15, size=0) 
plt.setp(ax.get_xticklabels(), rotation=0) 

plt.show() 

enter image description here

関連する問題