barh在柱状图之间产生了不规则的间距。

7
我一直在生成类似这样的条形图:

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来生成均匀间隔的柱形图,但这只能部分起作用,我不确定具体原因。

我在想你的问题可能与所有这些条形图都很拥挤有关,但是我已经尝试了从5到50个条形图的代码,这里没有任何问题。 - Ricardo Cárdenes
我有一种感觉,这可能是像素放置舍入问题。例如,如果您有一个高度为8个像素的图像,并且想要在中心绘制一条线,您会将其绘制在第4个像素行还是第5个像素行?无论哪种方式都看起来很糟糕。 - user1127062
顺便提一下,即使是一个微不足道的测试用例,我也得到了糟糕的结果:from numpy import * from pylab import * data = zeros(50)+10 ind = arange(10) barh(ind,data) show()` 看起来很糟糕。 - user1127062
Matplotlib的版本是多少?也许你遇到了一个bug:? - Ricardo Cárdenes
抱歉,是打错了。这是从 bar(arange(50),zeros(50)+1) 得到的样本输出:http://i.imgur.com/wqNrs.png 它几乎从来没有很好地对它们进行间距处理。至于版本:python-2.7.2(32位Windows),mpl-1.1.0,numpy-1.6.1。 - user1127062
我已经在某种程度上解决了这个问题,虽然解决方案不是很完美,但我打算写一篇如何生成像素精确的条形图的文章,并在这里发布给任何感兴趣的人。可能需要一天时间来完成这个。 - user1127062
1个回答

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

原生的“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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接