简体   繁体   中英

How to remove gaps in x axis in matplotlib bar chart?

I have this simple example:

from matplotlib import pyplot as plt
plt.bar(x=[0,1,2], height=[10,8,6], width=0.5)
plt.show()

How can I remove the 0.5, 1.5 between the bars so that the x axis has integers of 0, 1, 2 only? Thanks

在此处输入图像描述

Just add plt.xticks(range(3)) .

from matplotlib import pyplot as plt
plt.bar(x=[0,1,2], height=[10,8,6], width=0.5)
plt.xticks(range(3))
plt.show()

在此处输入图像描述

Edit

If you have gaps between your data, just use your x-values as input for xticks .

Code:

from matplotlib import pyplot as plt

x_data = [0, 1, 2, 5, 7]
y_data = [10, 8, 6, 3, 12]
plt.bar(x=x_data, height=y_data, width=0.5)
plt.xticks(x_data)
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.

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