1

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)

这将创建下图: 在此处输入图像描述

现在我想更改图像下方添加的第二个 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 轴的标签)。

我发现解决类似问题的最相似问题是如何更改多个轴标签的字体大小(使用 host_subplot API 创建),它会更改字体大小属性(不是附加到 xaxis 刻度的单个标签)。

4

2 回答 2

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()

在这种情况下绘制的图就是您要查找的内容:

底轴刻度标签


为了增加这是一个小错误的假设,与以前相同的打印语句的输出返回与以前相似的表示形式。

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,但这似乎有点不确定。也许有更多知识的人可以验证。

于 2015-09-23T23:51:54.043 回答
1

Dimitris 的回答太棒了!无论如何,我将在下面描述我完成使用的解决方法(在得到他的答案之前)。策略是在图形上添加一个新轴,然后隐藏除 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)
于 2015-09-24T15:17:40.133 回答