MatplotlibDraw.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. import os
  2. import matplotlib
  3. matplotlib.use('TkAgg')
  4. import matplotlib.pyplot as mpl
  5. import matplotlib.transforms as transforms
  6. import numpy as np
  7. class MatplotlibDraw:
  8. """
  9. Simple interface for plotting. This interface makes use of
  10. Matplotlib for plotting.
  11. Some attributes that must be controlled directly (no set_* method
  12. since these attributes are changed quite seldom).
  13. ========================== ============================================
  14. Attribute Description
  15. ========================== ============================================
  16. allow_screen_graphics False means that no plot is shown on
  17. the screen. (Does not work yet.)
  18. arrow_head_width Size of arrow head.
  19. ========================== ============================================
  20. """
  21. line_colors = {'red': 'r', 'green': 'g', 'blue': 'b', 'cyan': 'c',
  22. 'magenta': 'm', 'purple': 'p',
  23. 'yellow': 'y', 'black': 'k', 'white': 'w',
  24. 'brown': 'brown', '': ''}
  25. def __init__(self):
  26. self.instruction_file = None
  27. self.allow_screen_graphics = True # does not work yet
  28. def __del__(self):
  29. if self.instruction_file:
  30. self.instruction_file.write('\nmpl.draw()\nraw_input()\n')
  31. self.instruction_file.close()
  32. def ok(self):
  33. """
  34. Return True if set_coordinate_system is called and
  35. objects can be drawn.
  36. """
  37. def adjust_coordinate_system(self, minmax, occupation_percent=80):
  38. """
  39. Given a dict of xmin, xmax, ymin, ymax values, and a desired
  40. filling of the plotting area of `occupation_percent` percent,
  41. set new axis limits.
  42. """
  43. x_range = minmax['xmax'] - minmax['xmin']
  44. y_range = minmax['ymax'] - minmax['ymin']
  45. new_x_range = x_range*100./occupation_percent
  46. x_space = new_x_range - x_range
  47. new_y_range = y_range*100./occupation_percent
  48. y_space = new_y_range - y_range
  49. self.ax.set_xlim(minmax['xmin']-x_space/2., minmax['xmax']+x_space/2.)
  50. self.ax.set_ylim(minmax['ymin']-y_space/2., minmax['ymax']+y_space/2.)
  51. def set_coordinate_system(self, xmin, xmax, ymin, ymax, axis=False,
  52. instruction_file=None, new_figure=True,
  53. xkcd=False):
  54. """
  55. Define the drawing area [xmin,xmax]x[ymin,ymax].
  56. axis: None or False means that axes with tickmarks
  57. are not drawn.
  58. instruction_file: name of file where all the instructions
  59. for the plotting program are stored (useful for debugging
  60. a figure or tailoring plots).
  61. """
  62. # Close file for previous figure and start new one
  63. # if not the figure file is the same
  64. if self.instruction_file is not None:
  65. if instruction_file == self.instruction_file.name:
  66. pass # continue with same file
  67. else:
  68. self.instruction_file.close() # make new py file for commands
  69. self.mpl = mpl
  70. if xkcd:
  71. self.mpl.xkcd()
  72. self.xmin, self.xmax, self.ymin, self.ymax = \
  73. float(xmin), float(xmax), float(ymin), float(ymax)
  74. self.xrange = self.xmax - self.xmin
  75. self.yrange = self.ymax - self.ymin
  76. self.axis = axis
  77. # Compute the right X11 geometry on the screen based on the
  78. # x-y ratio of axis ranges
  79. ratio = (self.ymax-self.ymin)/(self.xmax-self.xmin)
  80. self.xsize = 800 # pixel size
  81. self.ysize = self.xsize*ratio
  82. geometry = '%dx%d' % (self.xsize, self.ysize)
  83. # See http://stackoverflow.com/questions/7449585/how-do-you-set-the-absolute-position-of-figure-windows-with-matplotlib
  84. if isinstance(instruction_file, str):
  85. self.instruction_file = open(instruction_file, 'w')
  86. else:
  87. self.instruction_file = None
  88. self.mpl.ion() # important for interactive drawing and animation
  89. if self.instruction_file:
  90. self.instruction_file.write("""\
  91. import matplotlib.pyplot as mpl
  92. import matplotlib.transforms as transforms
  93. mpl.ion() # for interactive drawing
  94. """)
  95. # Default properties
  96. self.set_linecolor('red')
  97. self.set_linewidth(2)
  98. self.set_linestyle('solid')
  99. self.set_filled_curves() # no filling
  100. self.set_fontsize(14)
  101. self.arrow_head_width = 0.2*self.xrange/16
  102. self._make_axes(new_figure=new_figure)
  103. manager = self.mpl.get_current_fig_manager()
  104. manager.window.wm_geometry(geometry)
  105. def _make_axes(self, new_figure=False):
  106. if new_figure:
  107. self.fig = self.mpl.figure()
  108. self.ax = self.fig.gca()
  109. self.ax.set_xlim(self.xmin, self.xmax)
  110. self.ax.set_ylim(self.ymin, self.ymax)
  111. self.ax.set_aspect('equal') # extent of 1 unit is the same on the axes
  112. if not self.axis:
  113. self.mpl.axis('off')
  114. axis_cmd = "mpl.axis('off') # do not show axes with tickmarks\n"
  115. else:
  116. axis_cmd = ''
  117. if self.instruction_file:
  118. fig = 'fig = mpl.figure()\n' if new_figure else ''
  119. self.instruction_file.write("""\
  120. %s
  121. ax = fig.gca()
  122. xmin, xmax, ymin, ymax = %s, %s, %s, %s
  123. ax.set_xlim(xmin, xmax)
  124. ax.set_ylim(ymin, ymax)
  125. ax.set_aspect('equal')
  126. %s
  127. """ % (fig, self.xmin, self.xmax, self.ymin, self.ymax, axis_cmd))
  128. def inside(self, pt, exception=False):
  129. """Is point pt inside the defined plotting area?"""
  130. area = '[%s,%s]x[%s,%s]' % \
  131. (self.xmin, self.xmax, self.ymin, self.ymax)
  132. tol = 1E-14
  133. pt_inside = True
  134. if self.xmin - tol <= pt[0] <= self.xmax + tol:
  135. pass
  136. else:
  137. pt_inside = False
  138. if self.ymin - tol <= pt[1] <= self.ymax + tol:
  139. pass
  140. else:
  141. pt_inside = False
  142. if pt_inside:
  143. return pt_inside, 'point=%s is inside plotting area %s' % \
  144. (pt, area)
  145. else:
  146. msg = 'point=%s is outside plotting area %s' % (pt, area)
  147. if exception:
  148. raise ValueError(msg)
  149. return pt_inside, msg
  150. def set_linecolor(self, color):
  151. """
  152. Change the color of lines. Available colors are
  153. 'black', 'white', 'red', 'blue', 'green', 'yellow',
  154. 'magenta', 'cyan'.
  155. """
  156. self.linecolor = MatplotlibDraw.line_colors[color]
  157. def set_linestyle(self, style):
  158. """Change line style: 'solid', 'dashed', 'dashdot', 'dotted'."""
  159. if not style in ('solid', 'dashed', 'dashdot', 'dotted'):
  160. raise ValueError('Illegal line style: %s' % style)
  161. self.linestyle = style
  162. def set_linewidth(self, width):
  163. """Change the line width (int, starts at 1)."""
  164. self.linewidth = width
  165. def set_filled_curves(self, color='', pattern=''):
  166. """
  167. Fill area inside curves with specified color and/or pattern.
  168. A common pattern is '/' (45 degree lines). Other patterns
  169. include '-', '+', 'x', '\\', '*', 'o', 'O', '.'.
  170. """
  171. if color is False:
  172. self.fillcolor = ''
  173. self.fillpattern = ''
  174. else:
  175. self.fillcolor = color if len(color) == 1 else \
  176. MatplotlibDraw.line_colors[color]
  177. self.fillpattern = pattern
  178. def set_fontsize(self, fontsize=18):
  179. """
  180. Method for setting a common fontsize for text, unless
  181. individually specified when calling ``text``.
  182. """
  183. self.fontsize = fontsize
  184. def set_grid(self, on=False):
  185. self.mpl.grid(on)
  186. if self.instruction_file:
  187. self.instruction_file.write("\nmpl.grid(%s)\n" % str(on))
  188. def erase(self):
  189. """Erase the current figure."""
  190. self.mpl.delaxes()
  191. if self.instruction_file:
  192. self.instruction_file.write("\nmpl.delaxes() # erase\n")
  193. self._make_axes(new_figure=False)
  194. def plot_curve(self, x, y,
  195. linestyle=None, linewidth=None,
  196. linecolor=None, arrow=None,
  197. fillcolor=None, fillpattern=None,
  198. shadow=0, name=None):
  199. """Define a curve with coordinates x and y (arrays)."""
  200. #if not self.allow_screen_graphics:
  201. # mpl.ioff()
  202. #else:
  203. # mpl.ion()
  204. self.xdata = np.asarray(x, dtype=np.float)
  205. self.ydata = np.asarray(y, dtype=np.float)
  206. if linestyle is None:
  207. # use "global" linestyle
  208. linestyle = self.linestyle
  209. if linecolor is None:
  210. linecolor = self.linecolor
  211. if linewidth is None:
  212. linewidth = self.linewidth
  213. if fillcolor is None:
  214. fillcolor = self.fillcolor
  215. if fillpattern is None:
  216. fillpattern = self.fillpattern
  217. if shadow == 1:
  218. shadow = 3 # smallest displacement that is visible
  219. # We can plot fillcolor/fillpattern, arrow or line
  220. if self.instruction_file:
  221. import pprint
  222. if name is not None:
  223. self.instruction_file.write('\n# %s\n' % name)
  224. if not arrow:
  225. self.instruction_file.write(
  226. 'x = %s\n' % pprint.pformat(self.xdata.tolist()))
  227. self.instruction_file.write(
  228. 'y = %s\n' % pprint.pformat(self.ydata.tolist()))
  229. if fillcolor or fillpattern:
  230. if fillpattern != '':
  231. fillcolor = 'white'
  232. #print '%d coords, fillcolor="%s" linecolor="%s" fillpattern="%s"' % (x.size, fillcolor, linecolor, fillpattern)
  233. [line] = self.ax.fill(x, y, fillcolor, edgecolor=linecolor,
  234. linewidth=linewidth, hatch=fillpattern)
  235. if self.instruction_file:
  236. self.instruction_file.write("[line] = ax.fill(x, y, '%s', edgecolor='%s', linewidth=%d, hatch='%s')\n" % (fillcolor, linecolor, linewidth, fillpattern))
  237. elif arrow:
  238. # Note that a Matplotlib arrow is a line with the arrow tip
  239. # (do not draw the line in addition)
  240. if not arrow in ('->', '<-', '<->'):
  241. raise ValueError("arrow argument must be '->', '<-', or '<->', not %s" % repr(arrow))
  242. # Add arrow to first and/or last segment
  243. start = arrow == '<-' or arrow == '<->'
  244. end = arrow == '->' or arrow == '<->'
  245. if start:
  246. x_s, y_s = x[1], y[1]
  247. dx_s, dy_s = x[0]-x[1], y[0]-y[1]
  248. self._plot_arrow(x_s, y_s, dx_s, dy_s, '->',
  249. linestyle, linewidth, linecolor)
  250. if end:
  251. x_e, y_e = x[-2], y[-2]
  252. dx_e, dy_e = x[-1]-x[-2], y[-1]-y[-2]
  253. self._plot_arrow(x_e, y_e, dx_e, dy_e, '->',
  254. linestyle, linewidth, linecolor)
  255. else:
  256. # Plain line
  257. [line] = self.ax.plot(x, y, linecolor, linewidth=linewidth,
  258. linestyle=linestyle)
  259. if self.instruction_file:
  260. self.instruction_file.write("[line] = ax.plot(x, y, '%s', linewidth=%d, linestyle='%s')\n" % (linecolor, linewidth, linestyle))
  261. if shadow:
  262. # http://matplotlib.sourceforge.net/users/transforms_tutorial.html#using-offset-transforms-to-create-a-shadow-effect
  263. # shift the object over 2 points, and down 2 points
  264. dx, dy = shadow/72., -shadow/72.
  265. offset = transforms.ScaledTranslation(
  266. dx, dy, self.fig.dpi_scale_trans)
  267. shadow_transform = self.ax.transData + offset
  268. # now plot the same data with our offset transform;
  269. # use the zorder to make sure we are below the line
  270. if linewidth is None:
  271. linewidth = 3
  272. self.ax.plot(x, y, linewidth=linewidth, color='gray',
  273. transform=shadow_transform,
  274. zorder=0.5*line.get_zorder())
  275. if self.instruction_file:
  276. self.instruction_file.write("""
  277. # Shadow effect for last ax.plot
  278. dx, dy = 3/72., -3/72.
  279. offset = matplotlib.transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
  280. shadow_transform = ax.transData + offset
  281. self.ax.plot(x, y, linewidth=%d, color='gray',
  282. transform=shadow_transform,
  283. zorder=0.5*line.get_zorder())
  284. """ % linewidth)
  285. def display(self, title=None, show=True):
  286. """Display the figure."""
  287. if title is not None:
  288. self.mpl.title(title)
  289. if self.instruction_file:
  290. self.instruction_file.write('mpl.title("%s")\n' % title)
  291. if show:
  292. self.mpl.draw()
  293. if self.instruction_file:
  294. self.instruction_file.write('mpl.draw()\n')
  295. def savefig(self, filename, dpi=None):
  296. """Save figure in file. Set dpi=300 for really high resolution."""
  297. # If filename is without extension, generate all important formats
  298. ext = os.path.splitext(filename)[1]
  299. if not ext:
  300. # Create both PNG and PDF file
  301. self.mpl.savefig(filename + '.png', dpi=dpi)
  302. # Crop the PNG file
  303. failure = os.system('convert -trim %s.png %s.png' %
  304. (filename, filename))
  305. if failure:
  306. print 'convert from ImageMagick is not installed - needed for cropping PNG files'
  307. self.mpl.savefig(filename + '.pdf')
  308. failure = os.system('pdfcrop %s.pdf %s.pdf' %
  309. (filename, filename))
  310. if failure:
  311. print 'pdfcrop is not installed - needed for cropping PDF files'
  312. #self.mpl.savefig(filename + '.eps')
  313. if self.instruction_file:
  314. self.instruction_file.write('mpl.savefig("%s.png", dpi=%s)\n'
  315. % (filename, dpi))
  316. self.instruction_file.write('mpl.savefig("%s.pdf")\n'
  317. % filename)
  318. else:
  319. self.mpl.savefig(filename, dpi=dpi)
  320. if ext == '.png':
  321. failure = os.system('convert -trim %s %s' % (filename, filename))
  322. if failure:
  323. print 'convert from ImageMagick is not installed - needed for cropping PNG files'
  324. elif ext == '.pdf':
  325. failure = os.system('pdfcrop %s %s' % (filename, filename))
  326. if failure:
  327. print 'pdfcrop is not installed - needed for cropping PDF files'
  328. if self.instruction_file:
  329. self.instruction_file.write('mpl.savefig("%s", dpi=%s)\n'
  330. % (filename, dpi))
  331. def text(self, text, position, alignment='center', fontsize=0,
  332. arrow_tip=None):
  333. """
  334. Write `text` string at a position (centered, left, right - according
  335. to the `alignment` string). `position` is a point in the coordinate
  336. system.
  337. If ``arrow+tip != None``, an arrow is drawn from the text to a point
  338. (on a curve, for instance). The arrow_tip argument is then
  339. the (x,y) coordinates for the arrow tip.
  340. fontsize=0 indicates use of the default font as set by
  341. ``set_fontsize``.
  342. """
  343. if fontsize == 0:
  344. if hasattr(self, 'fontsize'):
  345. fontsize = self.fontsize
  346. else:
  347. raise AttributeError(
  348. 'No self.fontsize attribute to be used when text(...)\n'
  349. 'is called with fontsize=0. Call set_fontsize method.')
  350. x, y = position
  351. if arrow_tip is None:
  352. self.ax.text(x, y, text, horizontalalignment=alignment,
  353. fontsize=fontsize)
  354. if self.instruction_file:
  355. self.instruction_file.write("""\
  356. ax.text(%g, %g, %s,
  357. horizontalalignment=%s, fontsize=%d)
  358. """ % (x, y, repr(text), repr(alignment), fontsize))
  359. else:
  360. if not len(arrow_tip) == 2:
  361. raise ValueError('arrow_tip=%s must be (x,y) pt.' % arrow)
  362. pt = arrow_tip
  363. self.ax.annotate(text, xy=pt, xycoords='data',
  364. textcoords='data', xytext=position,
  365. horizontalalignment=alignment,
  366. verticalalignment='top',
  367. fontsize=fontsize,
  368. arrowprops=dict(arrowstyle='->',
  369. facecolor='black',
  370. #linewidth=2,
  371. linewidth=1,
  372. shrinkA=5,
  373. shrinkB=5))
  374. if self.instruction_file:
  375. self.instruction_file.write("""\
  376. ax.annotate('%s', xy=%s, xycoords='data',
  377. textcoords='data', xytext=%s,
  378. horizontalalignment='%s',
  379. verticalalignment='top',
  380. fontsize=%d,
  381. arrowprops=dict(arrowstyle='->',
  382. facecolor='black',
  383. linewidth=2,
  384. shrinkA=5,
  385. shrinkB=5))
  386. """ % (text, pt, position, alignment, fontsize))
  387. # Drawing annotations with arrows:
  388. #http://matplotlib.sourceforge.net/users/annotations_intro.html
  389. #http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/annotation_demo2.py
  390. #http://matplotlib.sourceforge.net/users/annotations_intro.html
  391. #http://matplotlib.sourceforge.net/users/annotations_guide.html#plotting-guide-annotation
  392. def _plot_arrow(self, x, y, dx, dy, style='->',
  393. linestyle=None, linewidth=None, linecolor=None):
  394. """Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'."""
  395. if linestyle is None:
  396. # use "global" linestyle
  397. linestyle = self.linestyle
  398. if linecolor is None:
  399. linecolor = self.linecolor
  400. if linewidth is None:
  401. linewidth = self.linewidth
  402. if style == '->' or style == '<->':
  403. self.mpl.arrow(x, y, dx, dy, hold=True,
  404. facecolor=linecolor,
  405. edgecolor=linecolor,
  406. linestyle=linestyle,
  407. linewidth=linewidth,
  408. head_width=self.arrow_head_width,
  409. #head_width=0.1,
  410. #width=1, # width of arrow body in coordinate scale
  411. length_includes_head=True,
  412. shape='full')
  413. if self.instruction_file:
  414. self.instruction_file.write("""\
  415. mpl.arrow(x=%g, y=%g, dx=%g, dy=%g,
  416. facecolor='%s', edgecolor='%s',
  417. linestyle='%s',
  418. linewidth=%g, head_width=0.1,
  419. length_includes_head=True,
  420. shape='full')
  421. """ % (x, y, dx, dy, linecolor, linecolor, linestyle, linewidth))
  422. if style == '<-' or style == '<->':
  423. self.mpl.arrow(x+dx, y+dy, -dx, -dy, hold=True,
  424. facecolor=linecolor,
  425. edgecolor=linecolor,
  426. linewidth=linewidth,
  427. head_width=0.1,
  428. #width=1,
  429. length_includes_head=True,
  430. shape='full')
  431. if self.instruction_file:
  432. self.instruction_file.write("""\
  433. mpl.arrow(x=%g, y=%g, dx=%g, dy=%g,
  434. facecolor='%s', edgecolor='%s',
  435. linewidth=%g, head_width=0.1,
  436. length_includes_head=True,
  437. shape='full')
  438. """ % (x+dx, y+dy, -dx, -dy, linecolor, linecolor, linewidth))
  439. def arrow2(self, x, y, dx, dy, style='->'):
  440. """Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'."""
  441. self.ax.annotate('', xy=(x+dx,y+dy), xytext=(x,y),
  442. arrowprops=dict(arrowstyle=style,
  443. facecolor='black',
  444. linewidth=1,
  445. shrinkA=0,
  446. shrinkB=0))
  447. if self.instruction_file:
  448. self.instruction_file.write("""
  449. ax.annotate('', xy=(%s,%s), xytext=(%s,%s),
  450. arrowprops=dict(arrowstyle=%s,
  451. facecolor='black',
  452. linewidth=1,
  453. shrinkA=0,
  454. shrinkB=0))
  455. """ % (x+dx, y+dy, x, y, style))
  456. def _test():
  457. d = MatplotlibDraw(0, 10, 0, 5, instruction_file='tmp3.py', axis=True)
  458. d.set_linecolor('magenta')
  459. d.set_linewidth(6)
  460. # triangle
  461. x = np.array([1, 4, 1, 1]); y = np.array([1, 1, 4, 1])
  462. d.set_filled_curves('magenta')
  463. d.plot_curve(x, y)
  464. d.set_filled_curves(False)
  465. d.plot_curve(x+4, y)
  466. d.text('some text1', position=(8,4), arrow_tip=(6, 1), alignment='left',
  467. fontsize=18)
  468. pos = np.array((7,4.5)) # numpy points work fine
  469. d.text('some text2', position=pos, arrow_tip=(6, 1), alignment='center',
  470. fontsize=12)
  471. d.set_linewidth(2)
  472. d.arrow(0.25, 0.25, 0.45, 0.45)
  473. d.arrow(0.25, 0.25, 0.25, 4, style='<->')
  474. d.arrow2(4.5, 0, 0, 3, style='<->')
  475. x = np.linspace(0, 9, 201)
  476. y = 4.5 + 0.45*np.cos(0.5*np.pi*x)
  477. d.plot_curve(x, y, arrow='end')
  478. d.display()
  479. raw_input()
  480. if __name__ == '__main__':
  481. _test()