2013-05-10 102 views
8

我花了最近几天试图找到一种方法来从3D坐标图中的轴上移除微小的边距。我尝试了ax.margins(0)ax.autoscale_view('tight')等方法,但这些小毛利仍然存在。特别是,我不喜欢柱状图提升,即它们的底部不处于零水平 - 请参见示例图像。删除三维图中的坐标轴边距

unwanted margins on all axes

在gnuplot的,我会用 “设置为0 xy平面”。在matplotlib中,由于两边的每个轴都有边距,所以能够控制它们中的每一个都是非常好的。

编辑:下面 HYRY的解决方案工作良好,但“X”轴获取= 0在Y处绘制在它的网格线:

strange axis

+0

这将真正帮助,如果你可以添加代码你用来制作情节,所以我们有一个起点。然后,人们可以更容易地复制粘贴代码,然后找到针对此特定问题的解决方案。 – hooy 2013-05-10 19:46:53

+0

很多示例代码[here](http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html)(“Bar plot”示例与我上面的示例相似)。 – dolphin 2013-05-10 20:44:30

回答

6

没有属性或方法,其可以修改此边距。您需要修补源代码。下面是一个例子:

from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
import numpy as np 
###patch start### 
from mpl_toolkits.mplot3d.axis3d import Axis 
if not hasattr(Axis, "_get_coord_info_old"): 
    def _get_coord_info_new(self, renderer): 
     mins, maxs, centers, deltas, tc, highs = self._get_coord_info_old(renderer) 
     mins += deltas/4 
     maxs -= deltas/4 
     return mins, maxs, centers, deltas, tc, highs 
    Axis._get_coord_info_old = Axis._get_coord_info 
    Axis._get_coord_info = _get_coord_info_new 
###patch end### 

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): 
    xs = np.arange(20) 
    ys = np.random.rand(20) 

    # You can provide either a single color or an array. To demonstrate this, 
    # the first bar of each set will be colored cyan. 
    cs = [c] * len(xs) 
    cs[0] = 'c' 
    ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8) 

ax.set_xlabel('X') 
ax.set_ylabel('Y') 
ax.set_zlabel('Z') 

plt.show() 

结果是:

enter image description here

编辑

要更改网格线的颜色:

for axis in (ax.xaxis, ax.yaxis, ax.zaxis): 
    axis._axinfo['grid']['color'] = 0.7, 1.0, 0.7, 1.0 

艾迪T2

集X &ŸLIM:

ax.set_ylim3d(-1, 31) 
ax.set_xlim3d(-1, 21) 
+0

谢谢,它的工作......(1)如果我改变了'c,z in zip(['r','g','b','y'],[30,20,10,2] )',为什么'X'轴会变成粗虚线样式? (2)如何更改网格线的颜色? 'ax.grid(color ='blue')'不起作用。 – dolphin 2013-05-11 12:27:05

+0

@dolphin,你可以发布(1)的结果吗?对于(2),颜色不能被某些API修改,我添加了改变隐藏的_axinfo字典的代码。 – HYRY 2013-05-11 13:25:14

+0

感谢(2)!令人遗憾的是,matplotlib的复杂性和灵活性导致需要单独搜索的许多“黑客”,直观的解决方案有时有效,有时不行。关于(1),我无法在评论中发布图片,所以我粘贴了一段代码,希望能够复制它:-)现在我在原始问题中添加了另一个图像作为编辑。 – dolphin 2013-05-11 13:43:40

0

我不得不稍微调整接受的解决方案,因为在我的情况下,x和y轴(而不是Z)有一个额外的保证金,其中,通过打印mins, maxs, deltas,竟然是deltas * 6.0/11。这里是更新的补丁,在我的情况下效果很好。

###patch start### 
from mpl_toolkits.mplot3d.axis3d import Axis 
def _get_coord_info_new(self, renderer): 
    mins, maxs, cs, deltas, tc, highs = self._get_coord_info_old(renderer) 
    correction = deltas * [1.0/4 + 6.0/11, 
          1.0/4 + 6.0/11, 
          1.0/4] 
    mins += correction 
    maxs -= correction 
    return mins, maxs, cs, deltas, tc, highs 
if not hasattr(Axis, "_get_coord_info_old"): 
    Axis._get_coord_info_old = Axis._get_coord_info 
Axis._get_coord_info = _get_coord_info_new 
###patch end### 

(我也改变了逻辑修补了一下周围,使编辑功能并重新加载其模块现在将按预期在Jupyter。)