MatplotlibDraw.py 22 KB

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