matplotlib条形图:空间栏

Smi*_*ith 18 python matplotlib python-3.x

如何使用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()
Run Code Online (Sandbox Code Playgroud)

swa*_*hai 23

尝试更换

plt.bar(range(len(my_dict)), my_dict.values(), align='center')
Run Code Online (Sandbox Code Playgroud)

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

  • 对不起,错误.对齐选项有两个选项:{'edge','center'}. (2认同)
  • 宽度解决问题很好,但实际上,宽度是条宽而不是条之间的空间。 (2认同)

Shi*_*Dua 6

有两种增加条形图之间空间的方法,供参考,这里是绘图功能

plt.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs)
Run Code Online (Sandbox Code Playgroud)

减少条的宽度

绘图功能具有控制条形宽度的width参数。如果减小宽度,则条形之间的间距将自动减小。默认情况下,您的宽度设置为0.8。

width = 0.5
Run Code Online (Sandbox Code Playgroud)

缩放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)
Run Code Online (Sandbox Code Playgroud)