MatplotlibDraw.py 22 KB

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