matplotlib条形图:隔开钢筋

a64a0gku  于 2022-12-23  发布在  其他
关注(0)|答案(4)|浏览(150)

如何增加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()
zour9fqk

zour9fqk1#

尝试替换

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)

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

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

pcww981p2#

有两种方法可以增加条形图之间的间距,此处的图函数可供参考

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

减小条形图的宽度

绘图函数有一个宽度参数,用于控制条形的宽度。如果减小宽度,条形之间的间距将自动减小。默认情况下,宽度设置为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)
rt4zxlrg

rt4zxlrg3#

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

fig, ax = plt.subplots(figsize=(20,20))

# The first parameter would be the x value, 
# by editing the delta between the x-values 
# you change the space between bars
plt.bar([i*2 for i in range(100)], y_values)

# The first parameter is the same as above, 
# but the second parameter are the actual 
# texts you wanna display
plt.xticks([i*2 for i in range(100)], labels)

for tick in ax.get_xticklabels():
    tick.set_rotation(90)
6yjfywim

6yjfywim4#

设置x轴限制,从稍负的值开始到稍大于图中条形数量的值,并在“条形图”命令中更改条形的宽度
例如,我对只有两个条形的条形图做了这个
坐标轴1坐标轴设置_xlim(-0.5,1.5)

相关问题