简体   繁体   中英

Adding extra space along the x-axis in matplotlib bar graph

I'm using matplotlib to draw a bar chart with 3 bars. I want to add some extra space along the x-axis (so that the x-axis line is drawn longer).

Below is what I have:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

dt = [1,3,2]
plt.figure()
xvals = range(len(dt))
plt.bar(xvals, dt, width=0.5)
plt.tick_params(bottom=False)
plt.xticks(xvals, ['a','b','c'])
plt.yticks(range(0,4), [0,1,2,3])

plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)

plt.show()

This code produces:

条形图

I simply want (note the elongated x-axis):

所需图表

Change the limits of the x-axis using xlim()

for ex:

plt.xlim(-0.5,3.5)  # adjust as necessary

在此处输入图像描述

Just add the following limits. Yo can use None as the left hand limit to let the plot choose the limit as the default value. Since the x-values are 0, 1, 2 and now you add the right hand side limit as 3, you will have an extended axis. Replace 3 by whatever value you want.

plt.xlim(None, 3)

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM