matplotlib barh在条形之间产生不稳定的间距

时间:2012-01-03 01:55:57

标签: python matplotlib

我一直在制作看起来像这样的条形图:

enter image description here

请注意,由于某种原因,标签上的垂直间距不均匀;我不确定这是否与我如何分配刻度或实际放置文本的任何机制有关。相关代码:

height_factor = 40.0
ind = np.linspace(0,len(sorted_totals)*height_factor,num=len(sorted_totals))
width = 0.25
fig = plt.figure(figsize=(15.5, 8.75),dpi=300)
p1 = plt.barh(ind,map(int,sorted_composite[:,0]),color='blue',align='center',height=height_factor)
p1 = plt.barh(ind,map(int,sorted_composite[:,2]),color=(0.75,0.1,0.1),align='center',height=height_factor)
plt.ylabel('# of Picks (blue) + # of Bans (red)')
plt.yticks(ind, sorted_totals[:,0])
plt.subplots_adjust(bottom=0.05, left=0.14,right=0.95,top=0.95)
plt.ylim([ind.min() - height_factor, ind.max() + height_factor])

我的数据存储在sorted_composite中,而ind是我用来放置条形的值(ytick位置)。我正在使用linspace来生成均匀间隔的条形图,这只是一种工作,我不确定为什么。

1 个答案:

答案 0 :(得分:2)

就像user1127062建议的那样,可能是你的代码很好。

如果您不需要将图表设为交互式,请将其另存为svg

如果你跑:

data = numpy.random.randn(10000)
pylab.hist(data,300)
pylab.savefig(fileName+'.svg',format='svg')

你会在图窗口中看到像素别名(条形宽度),但它已经在svg文件中消失了。

如果svg与你正在做的事情不兼容,那么“cairo”后端似乎可以最好地保存png文件。它们看起来和svg的截图一样好。

您可以通过运行来切换后端。

import matplotlib
# you have to change the backend before importing pylab
matplotlib.use('cairo') 
import pylab

raw“cairo”不支持show(),因此您无法在交互模式下使用它,也无法直接从程序中显示情节。

“GTKCairo”后端具有两全其美但未在默认安装中启用(至少不是我使用sudo apt-get install matplotlib获得的那个)

如果您正在使用Ubuntu,我认为您需要做的就是安装gtk,并重新编译matplotlib:

sudo apt-get install git-core python-gtk2-dev
git clone git://github.com/matplotlib/matplotlib.git
cd matplotlib
sudo python setup.py install

您可以使用以下方法检查哪个后端处于活动状态:

matplotlib.get_backend()

您可以通过搜索matplotlibrc文件来自动加载您喜欢的后端,我发现了我的文件:

/usr/local/lib/python2.7/dist-packages/matplotlib/mpl-data/matplotlibrc