Python 关闭子图中的轴
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25862026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Turn off axes in subplots
提问by Sergey Ivanov
I have the following code:
我有以下代码:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("lena.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
rank = 128
new_img = prune_matrix(rank, img)
axarr[0,1].imshow(new_img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" %rank)
rank = 32
new_img = prune_matrix(rank, img)
axarr[1,0].imshow(new_img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" %rank)
rank = 16
new_img = prune_matrix(rank, img)
axarr[1,1].imshow(new_img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" %rank)
plt.show()
However, the result is pretty ugly because of the values on the axes:
但是,由于轴上的值,结果非常难看:


How can I turn off axes values for all subplots simultaneously?
如何同时关闭所有子图的轴值?
采纳答案by Ffisegydd
You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.
您可以按照 Veedrac 评论中的建议(链接到此处)并稍作修改来关闭轴。
Rather than using plt.axis('off')you should use ax.axis('off')where axis a matplotlib.axesobject. To do this for your code you simple need to add axarr[0,0].axis('off')and so on for each of your subplots.
而不是使用plt.axis('off')你应该使用ax.axis('off')where axis a matplotlib.axesobject。要为您的代码执行此操作,您只需axarr[0,0].axis('off')为每个子图添加等等。
The code below shows the result (I've removed the prune_matrixpart because I don't have access to that function, in the future please submit fully working code.)
下面的代码显示了结果(我已经删除了该prune_matrix部分,因为我无权访问该功能,将来请提交完整的工作代码。)
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm
img = mpimg.imread("stewie.jpg")
f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')
axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')
axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')
axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')
plt.show()


Note:To turn off only the x or y axis you can use set_visible()e.g.:
注意:要仅关闭 x 或 y 轴,您可以使用set_visible()例如:
axarr[0,0].xaxis.set_visible(False) # Hide only x axis
回答by Nirmal
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
To turn off axes for all subplots, do either:
要关闭所有子图的轴,请执行以下任一操作:
[axi.set_axis_off() for axi in ax.ravel()]
or
或者
map(lambda axi: axi.set_axis_off(), ax.ravel())

