【问题标题】:How to remove frame from matplotlib (pyplot.figure vs matplotlib.figure ) (frameon=False Problematic in matplotlib)如何从 matplotlib 中删除框架(pyplot.figure vs matplotlib.figure)(frameon=False 在 matplotlib 中有问题)
【发布时间】:2013-02-01 05:55:45
【问题描述】:

为了去除图中的框架,我写了

frameon=False

pyplot.figure 完美搭配,但在matplotlib.Figure 下,它只会移除灰色背景,框架会保持不变。另外,我只希望线条显示出来,其余的图都是透明的。

使用 pyplot 我可以做我想做的事,我想用 matplotlib 做这件事,出于某种长期的原因,我不想提及以扩展我的问题。

【问题讨论】:

  • 你能澄清一下你在做什么吗? (即显示一个例子)你在使用savefig吗? (如果是这样,它会覆盖您在保存图形时设置的任何内容。)手动设置 fig.patch.set_visible(False) 是否有效?
  • 我使用的是 canvas.print_png(response),而不是 savefig。

标签: python matplotlib


【解决方案1】:

ax.axis('off'),正如 Joe Kington 所指出的,将删除除绘制线之外的所有内容。

对于那些只想删除框架(边框)并保留标签、代码等的人,可以通过访问轴上的spines 对象来实现。给定一个轴对象ax,以下内容应删除所有四个边的边框:

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

并且,如果从图中删除 xy 刻度:

 ax.get_xaxis().set_ticks([])
 ax.get_yaxis().set_ticks([])

【讨论】:

  • 我喜欢这个去除顶部和右侧的刺
  • 只是补充:当您还想删除刻度时:ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom')
  • 另外,如果您还没有轴对象,请使用 ax=gca() 创建轴对象。
  • 这应该是公认的答案。 "ax.axis("off")" 删除所有内容,例如:x 和 y 标签、x 和 y 刻度以及绘图中的所有 (4) 个边框。为了更好地定制,每个元素都应该以不同的方式处理。
【解决方案2】:

首先,如果您使用的是savefig,请注意保存时它将覆盖图形的背景颜色,除非您另外指定(例如fig.savefig('blah.png', transparent=True))。

但是,要在屏幕上移除坐标轴和图形的背景,您需要将 ax.patchfig.patch 都设置为不可见。

例如

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

for item in [fig, ax]:
    item.patch.set_visible(False)

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

(当然,在SO的白色背景上你是看不出来区别的,但一切都是透明的……)

如果您不想显示除线条以外的任何内容,也可以使用 ax.axis('off') 关闭轴:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot(range(10))

fig.patch.set_visible(False)
ax.axis('off')

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

不过,在这种情况下,您可能希望轴占据整个图形。如果您手动指定轴的位置,您可以让它占据整个图形(或者,您可以使用subplots_adjust,但这对于单个轴的情况更简单)。

import matplotlib.pyplot as plt

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

ax.plot(range(10))

with open('test.png', 'w') as outfile:
    fig.canvas.print_png(outfile)

【讨论】:

  • 这样就解决了一半的问题。但我也希望这个黑框矩形是不可见的。所以只有蓝线应该是可见的。
  • 哦,好吧,那样的话就更简单了。只需使用ax.axis('off')(您仍然需要关闭图框)。
  • 谢谢,有没有办法保留ticklabels,如:我只想要标签ax.set_yticklabels(('G1', 'G2', 'G3'))
  • 这太好了,我在这里将它用于另一个应用程序:stackoverflow.com/questions/4092927/…
  • print_png() 在 python 3 上为我抛出了一个 TypeError: write() argument must be str, not bytes 异常。需要以写入二进制文件 ('wb') 的形式打开文件才能正常工作。
【解决方案3】:

在新版本的 matplotlib 中摆脱丑陋框架的最简单方法:

import matplotlib.pyplot as plt
plt.box(False)

如果您确实必须始终使用面向对象的方法,请执行以下操作:ax.set_frame_on(False)

【讨论】:

  • 谢谢!这可能是最干净的解决方案!
  • 当使用面向对象的方法时,我用ax.set_frame_on(False) 取得了成功,它做同样的事情。也许包括在上面的答案中。
  • 这会删除整个框/矩形,而不仅仅是框架/边框。可能是也可能不是你想要的。
【解决方案4】:

@peeol's excellent answer 的基础上,您也可以通过以下方式移除框架

for spine in plt.gca().spines.values():
    spine.set_visible(False)

举个例子(整个代码示例可以在这篇文章的末尾找到),假设你有一个这样的条形图,

您可以使用上述命令删除框架,然后保留 x-ytick 标签(图未显示)或将它们删除

plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

在这种情况下,可以直接标记条形;最终的情节可能是这样的(代码可以在下面找到):

这是生成绘图所需的全部代码:

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

xvals = list('ABCDE')
yvals = np.array(range(1, 6))

position = np.arange(len(xvals))

mybars = plt.bar(position, yvals, align='center', linewidth=0)
plt.xticks(position, xvals)

plt.title('My great data')
# plt.show()

# get rid of the frame
for spine in plt.gca().spines.values():
    spine.set_visible(False)

# plt.show()
# remove all the ticks and directly label each bar with respective value
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

# plt.show()

# direct label each bar with Y axis values
for bari in mybars:
    height = bari.get_height()
    plt.gca().text(bari.get_x() + bari.get_width()/2, bari.get_height()-0.2, str(int(height)),
                 ha='center', color='white', fontsize=15)
plt.show()

【讨论】:

    【解决方案5】:

    正如我回答 here 一样,您可以通过样式设置(样式表或 rcParams)从所有绘图中删除刺:

    import matplotlib as mpl
    
    mpl.rcParams['axes.spines.left'] = False
    mpl.rcParams['axes.spines.right'] = False
    mpl.rcParams['axes.spines.top'] = False
    mpl.rcParams['axes.spines.bottom'] = False
    

    【讨论】:

      【解决方案6】:

      问题

      我在使用轴时遇到了类似的问题。类参数是frameon,但kwarg 是frame_onaxes_api
      >>> plt.gca().set(frameon=False)
      AttributeError: Unknown property frameon

      解决方案

      frame_on

      示例

      data = range(100)
      import matplotlib.pyplot as plt
      fig, ax = plt.subplots()
      ax.plot(data)
      #ax.set(frameon=False)  # Old
      ax.set(frame_on=False)  # New
      plt.show()
      

      【讨论】:

        【解决方案7】:
        df = pd.DataFrame({
        'client_scripting_ms' : client_scripting_ms,
         'apimlayer' : apimlayer, 'server' : server
        }, index = index)
        
        ax = df.plot(kind = 'barh', 
             stacked = True,
             title = "Chart",
             width = 0.20, 
             align='center', 
             figsize=(7,5))
        
        plt.legend(loc='upper right', frameon=True)
        
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        
        ax.yaxis.set_ticks_position('left')
        ax.xaxis.set_ticks_position('right')
        

        【讨论】:

          【解决方案8】:

          我曾经这样做过:

          from pylab import *
          axes(frameon = 0)
          ...
          show()
          

          【讨论】:

            【解决方案9】:
            plt.axis('off')
            plt.savefig(file_path, bbox_inches="tight", pad_inches = 0)
            

            plt.savefig 本身就有这些选项,只需要在之前设置轴关闭

            【讨论】:

              【解决方案10】:
              plt.box(False)
              plt.xticks([])
              plt.yticks([])
              plt.savefig('fig.png')
              

              应该可以解决问题。

              【讨论】:

                【解决方案11】:

                这是另一种解决方案:

                img = io.imread(crt_path)
                
                fig = plt.figure()
                fig.set_size_inches(img.shape[1]/img.shape[0], 1, forward=False) # normalize the initial size
                ax = plt.Axes(fig, [0., 0., 1., 1.]) # remove the edges
                ax.set_axis_off() # remove the axis
                fig.add_axes(ax)
                
                ax.imshow(img)
                
                plt.savefig(file_name+'.png', dpi=img.shape[0]) # de-normalize to retrieve the original size
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2022-01-12
                  • 1970-01-01
                  • 2021-11-24
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多