在 matplotlib 图中隐藏轴文本

发布于 2024-08-19 20:08:08 字数 1052 浏览 3 评论 0原文

我试图在任一轴上绘制一个没有刻度线或数字的图形(我使用传统意义上的轴,而不是 matplotlib 命名法!)。我遇到的一个问题是 matplotlib 通过减去值 N 来调整 x(y)ticklabels,然后在轴的末尾添加 N。

这可能很模糊,但下面的简化示例突出了这个问题,其中“6.18”是 N 的令人反感的值:

import matplotlib.pyplot as plt
import random
prefix = 6.18

rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
    xlabel_i.set_visible(False)
    xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():
    xlabel_i.set_fontsize(0.0)
    xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
    tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)

plt.show()

我想知道的三件事是:

  1. 如何首先关闭此行为(尽管在大多数情况下它很有用,但并不总是如此!)我已经浏览了 matplotlib.axis.XAxis 并且找不到任何合适的内容

  2. 如何使 N 消失(即 X. set_visible(False))

  3. 有没有更好的方法来执行上述操作?如果相关的话,我的最终绘图将是图中的 4x4 子图。

I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.

This may be vague, but the following simplified example highlights the issue, with '6.18' being the offending value of N:

import matplotlib.pyplot as plt
import random
prefix = 6.18

rx = [prefix+(0.001*random.random()) for i in arange(100)]
ry = [prefix+(0.001*random.random()) for i in arange(100)]
plt.plot(rx,ry,'ko')

frame1 = plt.gca()
for xlabel_i in frame1.axes.get_xticklabels():
    xlabel_i.set_visible(False)
    xlabel_i.set_fontsize(0.0)
for xlabel_i in frame1.axes.get_yticklabels():
    xlabel_i.set_fontsize(0.0)
    xlabel_i.set_visible(False)
for tick in frame1.axes.get_xticklines():
    tick.set_visible(False)
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)

plt.show()

The three things I would like to know are:

  1. How to turn off this behaviour in the first place (although in most cases it is useful, it is not always!) I have looked through matplotlib.axis.XAxis and cannot find anything appropriate

  2. How can I make N disappear (i.e. X.set_visible(False))

  3. Is there a better way to do the above anyway? My final plot would be 4x4 subplots in a figure, if that is relevant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

零度° 2024-08-26 20:08:09

如果您只想隐藏轴文本并保留网格线:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

执行 set_visible(False)set_ticks([]) 也会隐藏网格线。

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

じее 2024-08-26 20:08:09

如果您像我一样,在绘制图形时并不总是检索轴,ax,那么一个简单的解决方案是

plt.xticks([])
plt.yticks([])

If you are like me and don't always retrieve the axes, ax, when plotting the figure, then a simple solution would be to do

plt.xticks([])
plt.yticks([])
Saygoodbye 2024-08-26 20:08:09

我已经对这个图进行了颜色编码以简化该过程。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

输入图像描述这里

您可以使用这些命令完全控制图形,为了完成答案,我还添加了对脊柱的控制:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)

I've colour coded this figure to ease the process.

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)

enter image description here

You can have full control over the figure using these commands, to complete the answer I've add also the control over the spines:

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)

# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)
谁与争疯 2024-08-26 20:08:09

我实际上无法根据此处的任何代码片段(甚至是答案中接受的代码片段)渲染没有边框或轴数据的图像。在深入研究了一些 API 文档后,我找到了这段代码来渲染我的图像,

plt.axis('off')
plt.tick_params(axis='both', left=False, top=False, right=False, bottom=False, labelleft=False, labeltop=False, labelright=False, labelbottom=False)
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

我使用 tick_params 调用基本上关闭了可能渲染的任何额外信息,并且我的输出文件中有一个完美的图形。

I was not actually able to render an image without borders or axis data based on any of the code snippets here (even the one accepted at the answer). After digging through some API documentation, I landed on this code to render my image

plt.axis('off')
plt.tick_params(axis='both', left=False, top=False, right=False, bottom=False, labelleft=False, labeltop=False, labelright=False, labelbottom=False)
plt.savefig('foo.png', dpi=100, bbox_inches='tight', pad_inches=0.0)

I used the tick_params call to basically shut down any extra information that might be rendered and I have a perfect graph in my output file.

奢欲 2024-08-26 20:08:09

有点旧线程,但是,这似乎是使用最新版本的 matplotlib 的更快方法:

设置 x 轴的主要格式化程序

ax.xaxis.set_major_formatter(plt.NullFormatter())

Somewhat of an old thread but, this seems to be a faster method using the latest version of matplotlib:

set the major formatter for the x-axis

ax.xaxis.set_major_formatter(plt.NullFormatter())
愛放△進行李 2024-08-26 20:08:09

一种技巧可能是将刻度标签的颜色设置为白色以隐藏它!

plt.xticks(color='w')
plt.yticks(color='w')

或者更一般化(@Armin Okić),您可以将其设置为“None”

One trick could be setting the color of tick labels as white to hide it!

plt.xticks(color='w')
plt.yticks(color='w')

or to be more generalized (@Armin Okić), you can set it as "None".

蹲墙角沉默 2024-08-26 20:08:09

使用面向对象的 API 时,Axes 对象有两个有用的方法用于删除轴文本:set_xticklabels()set_xticks()

假设您使用以下方法创建绘图。

fig, ax = plt.subplots(1)
ax.plot(x, y)

如果您只是想删除刻度标签,则可以使用

ax.set_xticklabels([])

或完全删除刻度,您可以使用

ax.set_xticks([])

这些方法对于准确指定您想要刻度的位置以及如何标记它们非常有用。传递空列表将分别导致没有刻度或没有标签。

When using the object oriented API, the Axes object has two useful methods for removing the axis text, set_xticklabels() and set_xticks().

Say you create a plot using

fig, ax = plt.subplots(1)
ax.plot(x, y)

If you simply want to remove the tick labels, you could use

ax.set_xticklabels([])

or to remove the ticks completely, you could use

ax.set_xticks([])

These methods are useful for specifying exactly where you want the ticks and how you want them labeled. Passing an empty list results in no ticks, or no labels, respectively.

夜吻♂芭芘 2024-08-26 20:08:09

您可以简单地将 xlabel 设置为 None,直接在您的轴上。下面是使用seaborn的工作示例

from matplotlib import pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

ax = sns.boxplot(x="day", y="total_bill", data=tips)
ax.set(xlabel=None)

plt.show()

You could simply set xlabel to None, straight in your axis. Below an working example using seaborn

from matplotlib import pyplot as plt
import seaborn as sns

tips = sns.load_dataset("tips")

ax = sns.boxplot(x="day", y="total_bill", data=tips)
ax.set(xlabel=None)

plt.show()
听不够的曲调 2024-08-26 20:08:09

如果你有子图,就这样做

fig, axs = plt.subplots(1, 2, figsize=(16, 8))

ax[0].set_yticklabels([]) # x-axis
ax[0].set_xticklabels([]) # y-axis

Just do this in case you have subplots

fig, axs = plt.subplots(1, 2, figsize=(16, 8))

ax[0].set_yticklabels([]) # x-axis
ax[0].set_xticklabels([]) # y-axis
淡看悲欢离合 2024-08-26 20:08:09

如何让刻度标签保留但标签消失:

axs.xaxis.label.set_visible(False)

How to let the tick labels stay but the axis label go away:

axs.xaxis.label.set_visible(False)

一身仙ぐ女味 2024-08-26 20:08:09

尝试使用以下代码行:

plt.axis("off")

应该可以为您解决问题。

Try with the following line of code:

plt.axis("off")

Should solve the issue for you.

長街聽風 2024-08-26 20:08:09

要保持刻度线和网格线完整但隐藏刻度标签,请使用:

ax.xaxis.set_tick_params(labelcolor='none')
# Similar for the y axis.

这还有一个优点,即 Jupyter Notebook 交互式后端的鼠标悬停实用程序不受影响;大多数其他解决方案往往会导致鼠标悬停实用程序失效,即不显示绘图坐标。

To keep the ticks and grid lines intact but hide the tick labels, use:

ax.xaxis.set_tick_params(labelcolor='none')
# Similar for the y axis.

This also has the advantage that the mouse-over utility of the interactive backend of Jupyter Notebook is not affected; most of the other solutions tend to cause the mouse-over utility to defunct, i.e. not showing the plot coordinates.

败给现实 2024-08-26 20:08:08

您可以隐藏整个轴,而不是隐藏每个元素:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

或者,您可以将刻度设置为空列表:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

在第二个选项中,您仍然可以使用 plt.xlabel()plt.ylabel() 向轴添加标签。

Instead of hiding each element, you can hide the whole axis:

frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)

Or, you can set the ticks to an empty list:

frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

In this second option, you can still use plt.xlabel() and plt.ylabel() to add labels to the axes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文