繁体   English   中英

在 matplotlib 中,我可以将标签设置在图的底部但刻度线为零吗?

[英]In matplotlib, can I set labels to the bottom of the plot but have the tick marks at zero?

我想沿零轴设置刻度标签,但将标签放置在图的底部(类似于示例图)。 在 Excel 中很容易做,但我一直无法在这里找到 matplotlib 的解决方案。 我是 matplotlib 的新手,很抱歉,如果这很明显,但是已经搜索了几个小时并且无法弄清楚。

以下测试代码创建一个图,但在 y=0 处的 x 轴上没有刻度:

from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame({'x': ["NegFour", "NegThree", "NegTwo", "NegOne", "One", "Two", "Three", "Four"],
                   'y': [-4, -3, -2, -1, 1, 2, 3, 4]})
plt.figure()
plt.bar(x=df['x'], height=df['y'], width=.3)
plt.show()

期望的输出:

示例图

诀窍是在顶部轴上绘制刻度,在底部轴上绘制标签,然后将顶部轴放在零点处。 Axes.tick_params()似乎有最重要的选项。

from matplotlib import pyplot as plt
import pandas as pd

df = pd.DataFrame({'x': ["NegFour", "NegThree", "NegTwo", "NegOne", "One", "Two", "Three", "Four"],
                   'y': [-4, -3, -2, -1, 1, 2, 3, 4]})
fig = plt.figure()
plt.bar(x=df['x'], height=df['y'], width=.3)

ax = plt.gca()
# Put top x axis at zero
ax.spines['top'].set_position('zero')
# Don't draw lines for bottom and right axes.
ax.spines['bottom'].set_color('none')
ax.spines['right'].set_color('none')
# Draw ticks on top x axis, and leave labels on bottom.
ax.tick_params(axis='x', bottom=False, top=True, direction='inout')

plt.show()

结果如下:

示例图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM