MatplotlibDraw.py 21 KB

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