MatplotlibDraw.py 19 KB

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