0

我对在 pylab 中绘图比较陌生,这是一个问题。我有一个包含长度从 2 到 10 的单词的文本文件,现在我的任务是使用条形图绘制每个单词类别的频率。我能够编写脚本并绘制它,但是 xtick 标签搞砸了,我想知道这是什么原因。在此先感谢您的帮助。

two_letter=[]
three_letter=[]
four_letter=[]
five_letter=[]
six_letter=[]
seven_letter=[]
eight_letter=[]
nine_letter=[]
ten_letter=[]

inFile = open('words.txt')
for line in inFile.readlines():
    fields = line.split(' ')
    for word in fields:
        if len(word) == 2:
            two_letter.append(word)
        elif len(word) == 3:
            three_letter.append(word)
        elif len(word) == 4:
            four_letter.append(word)
        elif len(word) == 5:
            five_letter.append(word)
        elif len(word) == 6:
            six_letter.append(word)
        elif len(word) == 7:
            seven_letter.append(word)
        elif len(word) == 8:
            eight_letter.append(word)
        elif len(word) == 9:
            nine_letter.append(word)
        else: 
            len(word) == 10
            ten_letter.append(word)
two_l = len(two_letter)
three_l = len(three_letter)
four_l = len(four_letter)
five_l = len(five_letter)
six_l = len(six_letter)
seven_l = len(seven_letter)
eight_l = len(eight_letter)
nine_l = len(nine_letter)
ten_l = len(ten_letter)

all = [two_l,three_l,four_l,five_l,six_l,seven_l,eight_l,nine_l,ten_l]
cord = range(1,10)
labels = ["two_let", "three_let", "four_let", "five_let", "six_let", "seven_let", "eight_let", "nine_let", "ten_let"]


import pylab
pylab.bar(cord,all, color='#88aa33')
xticks(cord, labels, rotation='vertical')
pylab.show()

在此处输入图像描述

4

1 回答 1

1

您可以在 bar 命令中使用关键字参数align将标签放在条的中心:

pylab.bar(cord,all, color='#88aa33', align='center')

要为标签腾出更多空间,您可以使用以下subplots_adjust函数调整绘图的大小和位置:

subplots_adjust(bottom=0.25)

为标签腾出足够的空间也可以通过以下方式自动完成:

from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable
make_axes_area_auto_adjustable(gca())
于 2013-04-06T12:00:11.527 回答