I am trying to create a bar chart subplot in matplotlib with 2 bar charts,on the x axis. I have created the following image:
This has been created with the following code:
import pandas as pd
import matplotlib.pyplot as plt
ydata1=pd.Series.from_array([451,505])
ydata2=pd.Series.from_array([839,286])
fig, (ax1, ax2) = plt.subplots(1,2,sharex='col',sharey='row')
xlabels = ['x1', 'x2']
ax1.bar(xlabels,ydata1, 0.4, align='center') #0.4 is width of bar
ax2.bar(xlabels,ydata2, 0.4, align='center')
plt.show()
The problem I am having is I'd like to adjust the position of the bars so they are symmetrical and equally spaced from the edge of each facet, as opposed to on the left and right edges of each facet (as they currently are). Is there any way to adjust the position of the bars in matplotlib so that they are symmetrical?
Thanks
To obtain an exact margin depending on bar width and number of bars, note:
0, 1, ..., N-1
1-bar_width
0-bar_width/2
; to have an equal spacing between the bar and the left margin as between the bars themselves, the left margin can be set at 0-bar_width/2-(1-bar_width)
N-1+bar_width/2+(1-bar_width)
import matplotlib.pyplot as plt
import numpy as np
N = 8
ydata1 = np.random.randint(200, 800, N)
ydata2 = np.random.randint(200, 800, N)
fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', sharey='row')
xlabels = [f'x{i}' for i in range(1, N + 1)]
width = 0.4
ax1.bar(xlabels, ydata1, width, align='center')
ax2.bar(xlabels, ydata2, width, align='center')
margin = (1 - width) + width / 2
ax1.set_xlim(-margin, len(xlabels) - 1 + margin)
ax2.set_xlim(-margin, len(xlabels) - 1 + margin)
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.