#5 Control width and space in barplots

This post explains 1/ how to control width of bars in a barplot  2/ how to control space between them – with matplotlib.

Control space
 
# library
import matplotlib.pyplot as plt 

# Make fake dataset 
height = [3, 12, 5, 18, 45] 
bars = ('A', 'B', 'C', 'D', 'E') 

# Choose the position of each barplots on the x-axis (space=1,4,3,1) 
y_pos = [0,1,5,8,9] 

# Create bars 
plt.bar(y_pos, height) 

# Create names on the x-axis 
plt.xticks(y_pos, bars) 

# Show graphic 
plt.show()
Control width
 

# library 
import matplotlib.pyplot as plt 

# Make fake dataset 
height = [3, 12, 5, 18, 45] 
bars = ('A', 'B', 'C', 'D', 'E') 
# Choose the width of each bar and their positions
width = [0.1,0.2,3,1.5,0.3]
y_pos = [0,0.3,2,4.5,5.5]

# Make the plot
plt.bar(y_pos, height, width=width)
plt.xticks(y_pos, bars)
plt.show()

Leave a Reply

Your email address will not be published.