尝试在pyplot直方图上的x轴标签之间添加更多空间

时间:2014-07-10 09:20:21

标签: python-2.7 matplotlib histogram

我正在尝试从字典中创建类似

的直方图
words = {'STORES': 8, 'ELECTRIC': 15, 'CAPITAL': 7, 'FLORIDA': 6, '-CL': 35, 'NATURAL': 6, 'ELECTRONICS': 8, 'INDUSTRIES': 35, 'GROUP': 42, 'POWER': 11, '&': 38, 'HOLDINGS': 14, 'GAS': 10, 'GENERAL': 15, 'PRODUCTS': 8, 'AMERICA': 8, 'NATIONAL': 7, 'A': 31, 'B': 7, 'CENTRAL': 7, 'INTL': 14, 'ENERGY': 21, 'CORP': 288, 'SYSTEMS': 18, 'REALTY': 8, 'TECHNOLOGIES': 13, 'TECHNOLOGY': 6, 'PROPERTIES': 6, 'RESOURCES': 16, 'FIRST': 9, 'STACKOVERFLOW': 10, 'INDS': 8, 'VERIZON': 13, 'OF': 10, 'COMMUNICATIONS': 9, 'AMERICAN': 34, 'HELLO': 6}

x轴表示words.key(),y轴表示words.values()。我尝试了几种方法来制作漂亮的直方图。以下是我的一次尝试......

import matplotlib.pyplot as pl
import numpy as np

ax = pl.subplot(111)
width=1.0
ax.bar(range(0,len(words)), words.values(), width=width/2)
ax.set_xticks(np.arange(0,len(words)) + width/2)
ax.set_xticklabels(words.keys())
pl.show()

此代码的问题在于x轴上的标签彼此重叠,这使得直方图难以理解。有人能给我解决这种情况吗?我真的希望能够控制标签彼此分开的距离。此外,将所有栏杆排列在中央位置,而不是从左侧排列,这将是很好的。

提前致谢!

1 个答案:

答案 0 :(得分:1)

一些建议:

  • 更改图形的大小。最重要的是要注意比例:如果条形图中的列太多,它应该有更宽的比例。

  • 更改文字的方向。旋转90度使其更加清晰。

我尝试了以下代码,效果很好:

import matplotlib.pyplot as pl
import numpy as np

fig = pl.figure(figsize=(18,4)) #sets a different size (inches wide, inches tall)
ax = pl.subplot(111)
width=1.0
ax.bar(range(0,len(words)), words.values(), width=width/2)
ax.set_xticks(np.arange(0,len(words)) + width/2)
ax.set_xticklabels(words.keys())

locs, labels = pl.xticks() #gets labels
pl.setp(labels, rotation=90) #sets rotation of the labels

pl.show()

您也可以更改字体,但我不认为这里需要。