MatplotlibDraw.py 19 KB

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