Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to put gap between y axis and first bar in vertical barchart matplotlib

I have a barchart code snippet as below..When you run this,you get 4 bars ,the first of which lies against the y axis.Is it possible to put some gap between y axis and the first bar?

def plot_graph1():
    xvals = range(4)
    xnames=["one","two","three","four"]
    yvals = [10,30,40,20]
    width = 0.25
    yinterval = 10
    figure = plt.figure()
    plt.grid(True)
    plt.xlabel('x vals')
    plt.ylabel('y vals')
    plt.bar(xvals, yvals, width=width)
    plt.xticks([ x+(width/2) for x in  xvals],[x for x in xnames])
    plt.yticks(range(0,max(yvals),yinterval))
    figure.savefig("barchart.png",format="png")
    plt.show()
if __name__=='__main__':    
    plot_graph1()

The output is as below

barchart as produced by above code

Any help appreciated

thanks

mark

like image 638
markjason72 Avatar asked Jul 10 '11 16:07

markjason72


People also ask

How do I add space between bars in Matplotlib?

The space between bars can be added by using rwidth parameter inside the “plt. hist()” function. This value specifies the width of the bar with respect to its default width and the value of rwidth cannot be greater than 1.

How do I limit the y-axis in Python?

Make two variables for max and min values for Y-axis. Use ylim() method to limit the Y-axis range. Use bar() method to plot the bars. To display the figure, use show() method.

How do you set a range in a bar plot in Python?

One approach would be to use a LineCollection and set the linewidth to resemble a bar plot. To use a LineCollection you need to provide a set of x values that plot each range provided in data . To create the y values associated with your range, I used np. arange .


1 Answers

In your specific case, it's easiest to use plt.margins and plt.ylim(ymin=0). margins will act like axis('tight'), but leave the specified percentage of "padding", instead of scaling to the exact limits of the data.

Also, plt.bar has an align="center" option that simplifies your example somewhat.

Here's a slightly simplified version of your example above:

import matplotlib.pyplot as plt

def plot_graph1():
    xvals = range(4)
    xnames=["one","two","three","four"]
    yvals = [10,30,40,20]
    width = 0.25
    yinterval = 10

    figure = plt.figure()
    plt.grid(True)
    plt.xlabel('x vals')
    plt.ylabel('y vals')

    plt.bar(xvals, yvals, width=width, align='center')
    plt.xticks(xvals, xnames)
    plt.yticks(range(0,max(yvals),yinterval))
    plt.xlim([min(xvals) - 0.5, max(xvals) + 0.5])

    figure.savefig("barchart.png",format="png")
    plt.show()

if __name__=='__main__':    
    plot_graph1()

enter image description here

like image 120
Joe Kington Avatar answered Oct 08 '22 02:10

Joe Kington