如何更改使用host_subplot创建的轴的标签(来自AxesGrid工具包)

时间:2015-09-23 18:29:54

标签: python matplotlib axes multiple-axes

AxesGrid工具包提供了函数host_subplot,可以创建多个平行轴,如下面的代码所示:

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt


host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(bottom=0.15)
par2 = host.twiny()
par2.axis["bottom"] = par2.get_grid_helper().new_fixed_axis(loc="bottom", axes=par2, offset=(0, -30) )
par2.axis["bottom"].toggle(all=True)

创建下图: enter image description here

现在我想更改图像下方添加的第二个x轴的标签。我尝试了以下(除其他外):

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt


host = host_subplot(111, axes_class=AA.Axes)
par2 = host.twiny()
par2.axis["bottom"] = par2.get_grid_helper().new_fixed_axis(loc="bottom", axes=par2, offset=(0, -30) )

for item in par2.get_xticklabels(): 
    item.set_text('new label')

par2.axis["bottom"].toggle(all=True)

可悲的是,par2.get_xticklabels()似乎没有像我天真地预期的那样工作(即它不会返回x轴的标签)。

我发现解决类似问题的最相似的问题是How to change the font size for multiple axes labels (created with host_subplot API),这会更改字体大小属性(而不是附加到xaxis标记的单个标签)。

2 个答案:

答案 0 :(得分:2)

嗯,我在尝试找到答案时学到了一件事:IPython是一个 非常好的 帮助器。

无论如何,要达到目的。通过get_xticklabels()迭代每个条目,似乎有一些关于设置文本的错误。 通过使用set_text(my_text)进行分配,即使my_text确实传入了Text对象,但由于某种原因,它不会在事后发现它。

案例:

[item.set_text("Some Text") for item in par2.get_xticklabels()]

for item in par2.get_xticklabels():
    print item

# Prints
Text(0,0,'Some Text')
Text(0,0,'Some Text')
Text(0,0,'Some Text')
Text(0,0,'Some Text')
Text(0,0,'Some Text')
Text(0,0,'Some Text')

# plt.show() does not display these changes.

谢天谢地奇怪),设置标签 正常工作 通过 set_xticklabels()

进行时
# Omitting rest of script.

# Set as False or else the top axis also gets these labels.
# Try commenting the line out to view what I mean.
par2.axis["top"].set_visible(False)
par2.set_xticklabels(["THIS", "IS", "PROBABLY", "A", "LITTLE", "BUG"])

plt.show()

在这种情况下绘制的数字是您正在寻找的:

bottom axis tick labels

为了补充这个小错误的假设,与之前相同的print语句的输出返回与之前相似的表示。

for item in par2.get_xticklabels():
    print item

Text(0,0,'THIS')
Text(0,0,'IS')
Text(0,0,'PROBABLY')
Text(0,0,'A')
Text(0,0,'LITTLE')
Text(0,0,'BUG')

matplotlib我不是最好的,但这似乎不合适。也许有更多知识的人可以验证。

答案 1 :(得分:1)

迪米瑞斯'答案太棒了!无论如何,我将描述我完成使用的解决方法(在得到答案之前)。策略是在图上添加一个新轴,然后隐藏除x轴外的所有内容。该解决方案的唯一优势是不需要使用AxesGrid框架。

import matplotlib.pyplot as plt

def add_extra_xaxis(fig, x, labels, padding=35):
    """
    Add a x axis bellow the figure (indeed bellow the ax returned by fig.gca()) having the labels
    in the x positions. The axis is added by first adding an entire new axes and the hiding all
    parts, except the xaxis.

     Parameters
    ------------

    fig : Figure
        The figure where to add the xaxis.

    x : list
        List of numbers specifying the x positions.

    labels : list
        List of strings specifying the labels to place in the x positions.

    padding : int
        How much space should be added between the figure and the new x axis bellow it.

     Returns
    ---------

    new_ax : Axes
        Return the axes added to the image.

    """

    # Add some space bellow the figure
    fig.subplots_adjust(bottom=0.2)

    # Get current ax
    ax = fig.gca()

    # Add a new ax to the figure
    new_ax = fig.add_axes(ax.get_position())

    # Hide the the plot area and the yaxis
    new_ax.patch.set_visible(False)
    new_ax.yaxis.set_visible(False)

    # Hide spines (unless the boottom one)
    for spinename, spine in new_ax.spines.iteritems():
        if spinename != 'bottom':
            spine.set_visible(False)

    # Set the ....
    new_ax.spines['bottom'].set_position(('outward', padding))

    # Change tick labels
    plt.xticks([0] + x, [''] + labels) # the [0] and [''] stuff is to add an empty lable in the first position

    return new_ax


if __name__=='__main__':

    f, _ = plt.subplots()
    add_extra_xaxis(f, [1,3,5,7,10],['Now','it','should', 'work', ''], padding=30)