在matplotlib中,如何在图形的两侧显示轴?

问题描述 投票:0回答:4

我想用matplotlib绘制一个图,图的两侧都有轴,类似于这个图(颜色与这个问题无关):

plot

我怎样才能用

matplotlib
做到这一点?

注意:与示例图中显示的相反,我希望两个轴完全相同,并且只想显示一张图。添加两个轴只是为了使图表更容易阅读。

python graphics matplotlib plot
4个回答
76
投票

您可以使用 tick_params() (这是我在 Jupyter 笔记本中所做的):

import matplotlib.pyplot as plt

bar(range(10), range(10))
tick_params(labeltop=True, labelright=True)

生成此图像:

Bar plot with both x and y axis labeled the same

UPD:添加了一个简单的子图示例。您应该将

tick_params()
与轴对象一起使用。

此代码设置为仅显示顶部子图的顶部标签和底部子图的底部标签(带有相应的刻度):

import matplotlib.pyplot as plt

f, axarr = plt.subplots(2)

axarr[0].bar(range(10), range(10))
axarr[0].tick_params(labelbottom=False, labeltop=True, labelleft=False, labelright=False,
                     bottom=False, top=True, left=False, right=False)

axarr[1].bar(range(10), range(10, 0, -1))
axarr[1].tick_params(labelbottom=True, labeltop=False, labelleft=False, labelright=False,
                     bottom=True, top=False, left=False, right=False)

看起来像这样:

Subplots ticks config example


21
投票

在线文档中有几个相关示例:


2
投票

我之前已经使用以下方法完成了此操作:

# Create figure and initial axis    
fig, ax0 = plt.subplots()
# Create a duplicate of the original xaxis, giving you an additional axis object
ax1 = ax.twinx()
# Set the limits of the new axis from the original axis limits
ax1.set_ylim(ax0.get_ylim())

这将完全复制原始 y 轴。

例如:

ax = plt.gca()

plt.bar(range(3), range(1, 4))
plt.axhline(1.75, color="gray", ls=":")

twin_ax = ax.twinx()
twin_ax.set_yticks([1.75])
twin_ax.set_ylim(ax.get_ylim())


0
投票

文档非常有帮助。我取得了良好、一致的结果,如下所示:

ax0 = ax.twinx()
ax0.set_ylim(ax.get_ylim())
ax0.set_yticks(ax.get_yticks(), ax.get_yticklabels(),
               fontsize= 8)

其中 ax 是默认显示,y 的刻度和刻度标签位于左侧。第一行代码创建 ax0 与 ax (twinx()) 共享 x 轴。第二行设置 ax0 的 y 轴的最小值和最大值以匹配 ax 的 y 轴的最小值和最大值。最后一行设置 ax0 的 y 刻度和刻度标签以匹配 ax 的那些。

© www.soinside.com 2019 - 2024. All rights reserved.