matplotlib 条形图:间隔条形图

新手上路,请多包涵

我如何使用 matplotlib 条形图增加每个条形之间的空间,因为它们不断将自己塞到中心。 在此处输入图像描述 (这是目前的样子)

 import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def ww(self):#wrongwords text file

    with open("wrongWords.txt") as file:
        array1 = []
        array2 = []
        for element in file:
            array1.append(element)

        x=array1[0]
    s = x.replace(')(', '),(') #removes the quote marks from csv file
    print(s)
    my_list = ast.literal_eval(s)
    print(my_list)
    my_dict = {}

    for item in my_list:
        my_dict[item[2]] = my_dict.get(item[2], 0) + 1

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

    plt.show()

原文由 Smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 474
2 个回答

尝试更换

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

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

原文由 swatchai 发布,翻译遵循 CC BY-SA 3.0 许可协议

有 2 种方法可以增加条之间的空间供参考,这里是 plot 函数

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

减少栏的宽度

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

 width = 0.5

缩放 x 轴,使条形之间的距离更远

如果你想保持宽度不变,你将不得不在 x 轴上放置条形的位置留出空间。您可以使用任何缩放参数。例如

x = (range(len(my_dict)))
new_x = [2*i for i in x]

# you might have to increase the size of the figure
plt.figure(figsize=(20, 3))  # width:10, height:8

plt.bar(new_x, my_dict.values(), align='center', width=0.8)

原文由 ShikharDua 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题