matplotlib bar chart: space out bars

Question:

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

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def ww(self):#wrongwords text file

    with open("wrongWords.txt") as file:
        array1 = []
        array2 = [] 
        for element in file:
            array1.append(element)

        x=array1[0]
    s = x.replace(')(', '),(') #removes the quote marks from csv file
    print(s)
    my_list = ast.literal_eval(s)
    print(my_list)
    my_dict = {}

    for item in my_list:
        my_dict[item[2]] = my_dict.get(item[2], 0) + 1

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

    plt.show()
Asked By: Smith

||

Answers:

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)

The option align='edge' will eliminate white space on the left of the bar chart.

And width=0.3 sets the bars’ width smaller size than the default value.
The bars spacing will be adjusted accordingly.

For the labels along x-axis, they should be rotated 90 degrees to make them readable.

plt.xticks(range(len(my_dict)), my_dict.keys(), rotation='vertical')
Answered By: swatchai

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)
Answered By: ShikharDua

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)
Answered By: Christian Pao.

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)

Answered By: Nishad Kadam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.