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