matplotlib 如何增加条形图条形之间的间距

brccelvz  于 2023-04-21  发布在  其他
关注(0)|答案(4)|浏览(371)

如何使用matplotlib条形图增加每个条形图之间的空间,因为它们一直将其自身填充到中心.

(这是它目前的外观)

  1. import matplotlib.pyplot as plt
  2. import matplotlib.dates as mdates
  3. def ww(self):#wrongwords text file
  4. with open("wrongWords.txt") as file:
  5. array1 = []
  6. array2 = []
  7. for element in file:
  8. array1.append(element)
  9. x=array1[0]
  10. s = x.replace(')(', '),(') #removes the quote marks from csv file
  11. print(s)
  12. my_list = ast.literal_eval(s)
  13. print(my_list)
  14. my_dict = {}
  15. for item in my_list:
  16. my_dict[item[2]] = my_dict.get(item[2], 0) + 1
  17. plt.bar(range(len(my_dict)), my_dict.values(), align='center')
  18. plt.xticks(range(len(my_dict)), my_dict.keys())
  19. plt.show()
9fkzdhlc

9fkzdhlc1#

尝试替换

  1. plt.bar(range(len(my_dict)), my_dict.values(), align='center')

  1. plt.figure(figsize=(20, 3)) # width:20, height:3
  2. plt.bar(range(len(my_dict)), my_dict.values(), align='edge', width=0.3)

选项align='edge'将消除条形图左侧白色。
width=0.3设置条的宽度小于默认值。条的间距将相应调整。
对于沿着x轴的标签,应将其旋转90度以使其可读。

  1. plt.xticks(range(len(my_dict)), my_dict.keys(), rotation='vertical')
uinbv5nw

uinbv5nw2#

有两种方法可以增加条形图之间的间距。这里是绘图函数

  1. plt.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)

减小条形图宽度

plot函数有一个宽度参数,用于控制条形图的宽度。如果您减小宽度,条形图之间的间距将自动减小。默认情况下,宽度设置为0.8。

  1. width = 0.5

缩放x轴,使条形图彼此相距更远

如果你想保持宽度不变,你必须在x轴上放置条的地方留出空间。你可以使用任何缩放参数。

  1. x = (range(len(my_dict)))
  2. new_x = [2*i for i in x]
  3. # you might have to increase the size of the figure
  4. plt.figure(figsize=(20, 3)) # width:10, height:8
  5. plt.bar(new_x, my_dict.values(), align='center', width=0.8)
展开查看全部
pwuypxnk

pwuypxnk3#

这个答案可以改变条之间的间距,也可以旋转x轴上的标签。它还可以让你改变图形的大小。

  1. fig, ax = plt.subplots(figsize=(20,20))
  2. # The first parameter would be the x value,
  3. # by editing the delta between the x-values
  4. # you change the space between bars
  5. plt.bar([i*2 for i in range(100)], y_values)
  6. # The first parameter is the same as above,
  7. # but the second parameter are the actual
  8. # texts you wanna display
  9. plt.xticks([i*2 for i in range(100)], labels)
  10. for tick in ax.get_xticklabels():
  11. tick.set_rotation(90)
tvmytwxo

tvmytwxo4#

将x轴限值从略负的值设置为略大于图中条形数量的值,并在barplot命令中更改条形的宽度
例如,我为只有两个条形的条形图做了这个
ax1.axes.set_xlim(-0.5,1.5)

相关问题