Andy Andy - 1 year ago 93
Python Question

Add padding between bars and Y-Axis

I am building a bar chart using matplotlib using the code below. When my first or last column of data is 0, my first column is wedged against the Y-axis.

An example of this. Note that the first column is ON the x=0 point.

Zero first column

If I have data in this column, I get a huge padding between the Y-Axis and the first column as seen here. Note the additional bar, now at X=0. This effect is repeated if I have data in my last column as well.
Non-zero first column

My code is as follows:

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)):

fig = plt.figure(figsize=(6,4))
ax1 = fig.add_subplot(1,1,1),binNorm,align='center', label='Values')
plt.title("Demo Histogram")
plt.grid(b=True, which='major', color='grey', linestyle='--', alpha=0.35)
plt.ylabel("% of Count")

How can I set a constant margin between the Y-axis and my first/last bar?

Additionally, I realize it's labeled "Demo Histogram", that is a because I missed it when correcting problems discussed here.

Answer Source

I can't run the code snippet you gave, and even with some modification I couldn't replicate the big space. Aside from that, if you need to enforce a border to matplotlib, you ca do somthing like this:

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

The first term tells the axis to put the border at 10 units of distance from the minimum of your data, the None parameter teels it to keep the present value.

to put it into contest:

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

searching around stackoverflow I just learned a new trick: you can call

ax.margins( margin_you_desire )

to let automatically let matplotlib put that amount of space around your plot. It can also be configured differently between x and y.

In your case the best solution would be something like

ax.margins(0.01, None)

The little catch is that the unit is in axes unit, referred to the size of you plot, so a margin of 1 will put space around your plot at both sizes big as your present plot

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download