我在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()
答案 0 :(得分: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())