2012-04-29 13 views
16
import matplotlib.pyplot as plt 

gridnumber = range(1,4) 

b1 = plt.bar(gridnumber, [0.2, 0.3, 0.1], width=0.4, 
       label="Bar 1", align="center") 

b2 = plt.bar(gridnumber, [0.3, 0.2, 0.2], color="red", width=0.4, 
       label="Bar 2", align="center") 


plt.ylim([0,0.5]) 
plt.xlim([0,4]) 
plt.xticks(gridnumber) 
plt.legend() 
plt.show() 

現在、b1とb2は重なっています。どのように私はそうのようにそれらを別々にプロットします:matplotlibのサイトでexampleあり同じX座標を並べた棒グラフを並べる方法

enter image description here

答えて

22

。基本的には、の値をwidthに変更するだけです。関連するビットは次のとおりです。

import numpy as np 
import matplotlib.pyplot as plt 

N = 5 
menMeans = (20, 35, 30, 35, 27) 
menStd = (2, 3, 4, 1, 2) 

ind = np.arange(N) # the x locations for the groups 
width = 0.35  # the width of the bars 

fig = plt.figure() 
ax = fig.add_subplot(111) 
rects1 = ax.bar(ind, menMeans, width, color='royalblue', yerr=menStd) 

womenMeans = (25, 32, 34, 20, 25) 
womenStd = (3, 5, 2, 3, 3) 
rects2 = ax.bar(ind+width, womenMeans, width, color='seagreen', yerr=womenStd) 

# add some 
ax.set_ylabel('Scores') 
ax.set_title('Scores by group and gender') 
ax.set_xticks(ind + width/2) 
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) 

ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) 

plt.show() 
4

場合によっては、適切なバーの幅を見つけるのが難しい場合があります。私は通常、このnp.diffを使って適切な次元を見つけます。

import numpy as np 
import matplotlib.pyplot as plt 

#The data 
womenMeans = (25, 32, 34, 20, 25) 
menMeans = (20, 35, 30, 35, 27) 
indices = [5.5,6,7,8.5,8.9] 
#Calculate optimal width 
width = np.min(np.diff(indices))/3 

fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.bar(indices-width,womenMeans,width,color='b',label='-Ymin') 
ax.bar(indices,menMeans,width,color='r',label='Ymax') 
ax.set_xlabel('Test histogram') 
plt.show() 

これが結果です:

enter image description here

関連する問題