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)
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()
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.
Here we'll use the figsize() method to change the bar plot size. Import matplotlib. pyplot library. To change the figure size, use figsize argument and set the width and the height of the plot.
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)
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)
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With