Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib bar chart: space out bars

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() 
like image 533
Smith Avatar asked Nov 13 '16 14:11

Smith


People also ask

How do I change the spacing 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 you increase the size of a bar in Python?

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.


2 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) 
like image 117
swatchai Avatar answered Sep 23 '22 19:09

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) 
like image 34
ShikharDua Avatar answered Sep 25 '22 19:09

ShikharDua