import matplotlib.pyplot as plt gridnumber = range(1,4) b1 = plt.bar(gridnumber, [0.2, 0.3, 0.1], width=0.4, label="Bar 1", align="center") b2 = plt.bar(gridnumber, [0.3, 0.2, 0.2], color="red", width=0.4, label="Bar 2", align="center") plt.ylim([0,0.5]) plt.xlim([0,4]) plt.xticks(gridnumber) plt.legend() plt.show()
Currently b1 and b2 overlap each other. How do I plot them separately like so:
By using plt. subplot() method we create two subplots side by side. plt. bar() method is used to create multiple bar chart graphs.
As a variation of a bar chart, a side-by-side bar chart is similar to a stacked bar chart, except it puts bars side by side instead of stacking them. Both side-by-side bar and stacked bar charts add a second dimension based on a standard bar chart. But stacked bar charts tend to show the part-to-whole relation.
There is an example in the matplotlib site. Basically, you just shift the x
values by width
. Here is the relevant bit:
import numpy as np import matplotlib.pyplot as plt N = 5 menMeans = (20, 35, 30, 35, 27) menStd = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig = plt.figure() ax = fig.add_subplot(111) rects1 = ax.bar(ind, menMeans, width, color='royalblue', yerr=menStd) womenMeans = (25, 32, 34, 20, 25) womenStd = (3, 5, 2, 3, 3) rects2 = ax.bar(ind+width, womenMeans, width, color='seagreen', yerr=womenStd) # add some ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(ind + width / 2) ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') ) ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') ) plt.show()
Below answer will explain each and every line of code in the simplest manner possible:
# Numbers of pairs of bars you want N = 3 # Data on X-axis # Specify the values of blue bars (height) blue_bar = (23, 25, 17) # Specify the values of orange bars (height) orange_bar = (19, 18, 14) # Position of bars on x-axis ind = np.arange(N) # Figure size plt.figure(figsize=(10,5)) # Width of a bar width = 0.3 # Plotting plt.bar(ind, blue_bar , width, label='Blue bar label') plt.bar(ind + width, orange_bar, width, label='Orange bar label') plt.xlabel('Here goes x-axis label') plt.ylabel('Here goes y-axis label') plt.title('Here goes title of the plot') # xticks() # First argument - A list of positions at which ticks should be placed # Second argument - A list of labels to place at the given locations plt.xticks(ind + width / 2, ('Xtick1', 'Xtick3', 'Xtick3')) # Finding the best position for legends and putting it plt.legend(loc='best') plt.show()
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