matplotlib bar chart: space out bars

前端 未结 4 832
滥情空心
滥情空心 2021-01-01 10:28

How do I increase the space between each bar with matplotlib barcharts, as they keep cramming them self to the centre. (this is what it currently looks)

impo         


        
相关标签:
4条回答
  • 2021-01-01 10:48

    This answer changes the space between bars and it also rotate the labels on the x-axis. It also lets you change the figure size.

    fig, ax = plt.subplots(figsize=(20,20))
    
    # The first parameter would be the x value, 
    # by editing the delta between the x-values 
    # you change the space between bars
    plt.bar([i*2 for i in range(100)], y_values)
    
    # The first parameter is the same as above, 
    # but the second parameter are the actual 
    # texts you wanna display
    plt.xticks([i*2 for i in range(100)], labels)
    
    for tick in ax.get_xticklabels():
        tick.set_rotation(90)
    
    0 讨论(0)
  • 2021-01-01 10:57

    set your x axis limits starting from slightly negative value to slightly larger value than the number of bars in your plot and change the width of the bars in the barplot command

    for example I did this for a barplot with just two bars

    ax1.axes.set_xlim(-0.5,1.5)

    0 讨论(0)
  • 2021-01-01 11:01

    There are 2 ways to increase the space between the bars For reference here is the plot functions

    plt.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
    

    Decrease the width of the bar

    The plot function has a width parameter that controls the width of the bar. If you decrease the width the space between the bars will automatically reduce. Width for you is set to 0.8 by default.

    width = 0.5
    

    Scale the x-axis so the bars are placed further apart from each other

    If you want to keep the width constant you will have to space out where the bars are placed on x-axis. You can use any scaling parameter. For example

    x = (range(len(my_dict)))
    new_x = [2*i for i in x]
    
    # you might have to increase the size of the figure
    plt.figure(figsize=(20, 3))  # width:10, height:8
    
    plt.bar(new_x, my_dict.values(), align='center', width=0.8)
    
    0 讨论(0)
  • 2021-01-01 11:07

    Try replace

    plt.bar(range(len(my_dict)), my_dict.values(), align='center')
    

    with

    plt.figure(figsize=(20, 3))  # width:20, height:3
    plt.bar(range(len(my_dict)), my_dict.values(), align='edge', width=0.3)
    
    0 讨论(0)
提交回复
热议问题