2017-04-21 94 views
14

以下代碼僅顯示主類別['one','two','three','four','five','six']作爲x軸標籤。有一種方法顯示子類別['A','B','C','D']作爲輔助x軸標籤嗎? 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

我能想到的兩種選擇:1.下面主之一創建自組織二次X軸(見[此](http://stackoverflow.com/questions/31803817/how-to-add-second-x-axis-the-the-the-the-one-the-one-in-matplotlib)); 2.從'df.unstack()。plot.bar()'開始,然後更改圖形屬性。 – 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

相關問題