8 Nov 2016

matplotlib tips: draw circle, rectangle, save figure and maxmize figure

收藏到CSDN网摘
matplotlib是一个非常强大的python库,拥有众多作图函数与matlab类似的语法,使用非常方便.但是经常有一些小问题需要处理.这里记下解决方案,涉及到: 画圆, 画矩形, 保存图片, 和图片默认最大化. 以后如果碰到其他问题再添加.
# -*- coding: utf-8 -*-

import os
import matplotlib.pyplot as plt
import matplotlib.patches as patch


def save_fig(pfile,fig=None):
   ''' save specified figure or current active figure to a png file '''
   if not os.path.isfile(pfile):
      print "##ERROR: cannot open specified png file for writing"
      return -1
   else:
      if not fig: fig = plt.gcf()
      fig.savefig(pfile, dpi=300, bbox_inches='tight')
      print "figure saved: "+pfile
      return 0


def draw_circle(c, r, colour='b', isfill=False, line=1, fig=None):
   ''' draw a circle at the centre with specified diameter and colour '''
   if not fig: fig = plt.gcf()
   c1 = plt.Circle(c, r, color=colour, fill=isfill,
                   clip_on=False, linewidth=line)
   ax = fig.gca()
   ax.add_artist(c1)
   plt.axes().set_aspect('equal', 'datalim')
   ax.autoscale()


def add_circle(c, fig=None):
   if not fig: fig = plt.gcf()
   ax = fig.gca()
   ax.add_artist(c)
   plt.axes().set_aspect('equal', 'datalim')
   ax.autoscale()


def draw_rect(c, w, h, fig=None, isfill=False,
              fillcolour='b', bordercolour='b',
              alphanum=1, borderwidth=1):
   ''' draw a rectangle with corner c, width w and height h '''
   if not fig: fig = plt.gcf()
   ax = fig.gca()
   ax.add_patch(patch.Rectangle(c, w, h,
                                fill=isfill,
                                alpha=alphanum,
                                edgecolor=bordercolour,
                                facecolor=fillcolour,
                                linewidth=borderwidth))
   plt.axes().set_aspect('equal', 'datalim')
   ax.autoscale()


def max_fig():
   ''' maxmize the figure depend on the backend, works on all OSes '''
   backend = plt.get_backend().lower()
   fig_man = plt.get_current_fig_manager()
   if 'tk' in backend: # TkAgg
      fig_man.window.state('zoomed')
   elif 'wx' in backend: # WxAgg
      fig_man.frame.Maximize(True)
   elif 'qt' in backend: # QtAgg
      fig_man.window.showMaximized()


def set_title(title=''):
   ''' set title of the figure '''
   if title: plt.title(title)

# -------------------------------------------------------
if __name__=='__main__':
   fig = plt.figure("test")
#   plt.axis("off")

   x, y = 0, 0
   draw_circle([x, y], 10, 'r', 3)

   c2 = plt.Circle((20, 20), 5, color='b', fill=True)
   add_circle(c2)

   draw_rect([0, 0], 177.04, 44, borderwidth=3)

   print plt.get_backend()
   max_fig()
   plt.show()

   set_title()

No comments :

Post a Comment