2013-03-14 59 views
1

我使用下面的代碼使用matplotlib構建條形圖。當我的第一列或最後一列數據爲0時,我的第一列被楔入Y軸。在條形圖和Y軸之間添加填充

這是一個例子。請注意,第一列是在x = 0點上。

Zero first column

如果我在這列數據,我得到的Y軸和這裏看到的第一列之間的巨大空白。注意附加欄,現在在X = 0。如果我在最後一欄中有數據,則重複此效果。 Non-zero first column

我的代碼如下:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.ticker import MultipleLocator 

binVals = [0,5531608,6475325,1311915,223000,609638,291151,449434,1398731,2516755,3035532,2976924,2695079,1822865,1347155,304911,3562,157,5,0,0,0,0,0,0,0,0] 
binTot = sum(binVals) 
binNorm = [] 

for v in range(len(binVals)): 
    binNorm.append(float(binVals[v])/binTot) 

fig = plt.figure(figsize=(6,4)) 
ax1 = fig.add_subplot(1,1,1) 
ax1.bar(range(len(binNorm)),binNorm,align='center', label='Values') 
plt.legend(loc=1) 
plt.title("Demo Histogram") 
plt.xlabel("Value") 
plt.xticks(range(len(binLabels)),binLabels,rotation='vertical') 
plt.grid(b=True, which='major', color='grey', linestyle='--', alpha=0.35) 
ax1.xaxis.grid(False) 
plt.ylabel("% of Count") 
plt.subplots_adjust(bottom=0.15) 
plt.tight_layout() 
plt.show() 

如何設置Y軸和我的第一個/最後一棒之間保持恆定的距離呢?

此外,我意識到它被標記爲「演示直方圖」,那是因爲在糾正問題here時我錯過了它。

回答

9

我不能運行你給出的代碼片段,即使有一些修改,我無法複製大空間。除此之外,如果你需要強制執行邊界matplotlib,你CA做財產以後這樣的:

ax.set_xlim(min(your_data) - 10, None) 

的第一項告訴軸從最小的數據放在邊境的10個單位的距離, None參數調整它以保持當前值。

把它放到比賽:

from collections import Counter 
from pylab import * 
data = randint(20,size=1000) 
res = Counter(data) 
vals = arange(20) 
ax = gca() 
ax.bar(vals-0.4, [ res[i] for i in vals ], width=0.8) 
ax.set_xlim(min(data)-1, None) 
show() 

摸索計算器我只學會了一個新把戲:你可以打電話

ax.margins(margin_you_desire) 

讓自動讓matplotlib放的空間量在你的陰謀。它也可以在x和y之間進行不同的配置。

在你的情況下,最好的解決辦法是這樣的

ax.margins(0.01, None) 

小美中不足的是,本機在軸單位,提到了你的尺寸的情節,所以1保證金會把周圍空間你的情節在兩個大小都很大,因爲你現在的情節很大

0

問題是align='center'。去掉它。