如何更改使用 host_subplot 创建的轴的标签(来自 AxesGrid 工具包)
How to change the labels of an axis created with host_subplot (from AxesGrid toolkit)
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()
似乎没有像我天真地预期的那样工作(即它没有 return x 轴的标签)。
我发现解决类似问题的最相似问题是 How to change the font size for multiple axes labels (created with host_subplot API),它会更改字体大小 属性(不是附加到 xaxis 刻度的单个标签)。
好吧,我在尝试寻找答案时学到了一件事: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()
本案例中绘制的图形就是您要查找的图形:
为了补充这是一个小错误的假设,与之前相同的 print 语句的输出 returns 与之前类似的表示形式。
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
的最佳人选,但这看起来很可疑。也许有更多知识的人可以验证。
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)
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()
似乎没有像我天真地预期的那样工作(即它没有 return x 轴的标签)。
我发现解决类似问题的最相似问题是 How to change the font size for multiple axes labels (created with host_subplot API),它会更改字体大小 属性(不是附加到 xaxis 刻度的单个标签)。
好吧,我在尝试寻找答案时学到了一件事: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()
本案例中绘制的图形就是您要查找的图形:
为了补充这是一个小错误的假设,与之前相同的 print 语句的输出 returns 与之前类似的表示形式。
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
的最佳人选,但这看起来很可疑。也许有更多知识的人可以验证。
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)