MatplotlibDraw.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. # If filename is without extension, generate all important formats
  283. ext = os.path.splitext(filename)[1]
  284. if not ext:
  285. self.mpl.savefig(filename + '.png', dpi=300)
  286. self.mpl.savefig(filename + '.pdf')
  287. #self.mpl.savefig(filename + '.eps')
  288. else:
  289. self.mpl.savefig(filename, dpi=300)
  290. if self.instruction_file:
  291. self.instruction_file.write('mpl.savefig("%s", dpi=600)\n' %
  292. filename)
  293. def text(self, text, position, alignment='center', fontsize=0,
  294. arrow_tip=None):
  295. """
  296. Write `text` string at a position (centered, left, right - according
  297. to the `alignment` string). `position` is a point in the coordinate
  298. system.
  299. If ``arrow+tip != None``, an arrow is drawn from the text to a point
  300. (on a curve, for instance). The arrow_tip argument is then
  301. the (x,y) coordinates for the arrow tip.
  302. fontsize=0 indicates use of the default font as set by
  303. ``set_fontsize``.
  304. """
  305. if fontsize == 0:
  306. if hasattr(self, 'fontsize'):
  307. fontsize = self.fontsize
  308. else:
  309. raise AttributeError(
  310. 'No self.fontsize attribute to be used when text(...)\n'
  311. 'is called with fontsize=0. Call set_fontsize method.')
  312. x, y = position
  313. if arrow_tip is None:
  314. self.ax.text(x, y, text, horizontalalignment=alignment,
  315. fontsize=fontsize)
  316. if self.instruction_file:
  317. self.instruction_file.write("""\
  318. ax.text(%g, %g, %s,
  319. horizontalalignment=%s, fontsize=%d)
  320. """ % (x, y, repr(text), repr(alignment), fontsize))
  321. else:
  322. if not len(arrow_tip) == 2:
  323. raise ValueError('arrow_tip=%s must be (x,y) pt.' % arrow)
  324. pt = arrow_tip
  325. self.ax.annotate(text, xy=pt, xycoords='data',
  326. textcoords='data', xytext=position,
  327. horizontalalignment=alignment,
  328. verticalalignment='top',
  329. fontsize=fontsize,
  330. arrowprops=dict(arrowstyle='->',
  331. facecolor='black',
  332. #linewidth=2,
  333. linewidth=1,
  334. shrinkA=5,
  335. shrinkB=5))
  336. if self.instruction_file:
  337. self.instruction_file.write("""\
  338. ax.annotate('%s', xy=%s, xycoords='data',
  339. textcoords='data', xytext=%s,
  340. horizontalalignment='%s',
  341. verticalalignment='top',
  342. fontsize=%d,
  343. arrowprops=dict(arrowstyle='->',
  344. facecolor='black',
  345. linewidth=2,
  346. shrinkA=5,
  347. shrinkB=5))
  348. """ % (text, pt, position, alignment, fontsize))
  349. # Drawing annotations with arrows:
  350. #http://matplotlib.sourceforge.net/users/annotations_intro.html
  351. #http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/annotation_demo2.py
  352. #http://matplotlib.sourceforge.net/users/annotations_intro.html
  353. #http://matplotlib.sourceforge.net/users/annotations_guide.html#plotting-guide-annotation
  354. def plot_arrow(self, x, y, dx, dy, style='->',
  355. linestyle=None, linewidth=None, linecolor=None):
  356. """Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'."""
  357. if linestyle is None:
  358. # use "global" linestyle
  359. linestyle = self.linestyle
  360. if linecolor is None:
  361. linecolor = self.linecolor
  362. if linewidth is None:
  363. linewidth = self.linewidth
  364. if style == '->' or style == '<->':
  365. self.mpl.arrow(x, y, dx, dy, hold=True,
  366. facecolor=linecolor,
  367. edgecolor=linecolor,
  368. linewidth=linewidth,
  369. head_width=self.arrow_head_width,
  370. #head_width=0.1,
  371. #width=1, # width of arrow body in coordinate scale
  372. length_includes_head=True,
  373. shape='full')
  374. if self.instruction_file:
  375. self.instruction_file.write("""\
  376. mpl.arrow(x=%g, y=%g, dx=%g, dy=%g,
  377. facecolor='%s', edgecolor='%s',
  378. linewidth=%g, head_width=0.1,
  379. length_includes_head=True,
  380. shape='full')
  381. """ % (x, y, dx, dy, linecolor, linecolor, linewidth))
  382. if style == '<-' or style == '<->':
  383. self.mpl.arrow(x+dx, y+dy, -dx, -dy, hold=True,
  384. facecolor=linecolor,
  385. edgecolor=linecolor,
  386. linewidth=linewidth,
  387. head_width=0.1,
  388. #width=1,
  389. length_includes_head=True,
  390. shape='full')
  391. if self.instruction_file:
  392. self.instruction_file.write("""\
  393. mpl.arrow(x=%g, y=%g, dx=%g, dy=%g,
  394. facecolor='%s', edgecolor='%s',
  395. linewidth=%g, head_width=0.1,
  396. length_includes_head=True,
  397. shape='full')
  398. """ % (x+dx, y+dy, -dx, -dy, linecolor, linecolor, linewidth))
  399. def arrow2(self, x, y, dx, dy, style='->'):
  400. """Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'."""
  401. self.ax.annotate('', xy=(x+dx,y+dy), xytext=(x,y),
  402. arrowprops=dict(arrowstyle=style,
  403. facecolor='black',
  404. linewidth=1,
  405. shrinkA=0,
  406. shrinkB=0))
  407. if self.instruction_file:
  408. self.instruction_file.write("""
  409. ax.annotate('', xy=(%s,%s), xytext=(%s,%s),
  410. arrowprops=dict(arrowstyle=%s,
  411. facecolor='black',
  412. linewidth=1,
  413. shrinkA=0,
  414. shrinkB=0))
  415. """ % (x+dx, y+dy, x, y, style))
  416. def _test():
  417. d = MatplotlibDraw(0, 10, 0, 5, instruction_file='tmp3.py', axis=True)
  418. d.set_linecolor('magenta')
  419. d.set_linewidth(6)
  420. # triangle
  421. x = np.array([1, 4, 1, 1]); y = np.array([1, 1, 4, 1])
  422. d.set_filled_curves('magenta')
  423. d.plot_curve(x, y)
  424. d.set_filled_curves(False)
  425. d.plot_curve(x+4, y)
  426. d.text('some text1', position=(8,4), arrow_tip=(6, 1), alignment='left',
  427. fontsize=18)
  428. pos = np.array((7,4.5)) # numpy points work fine
  429. d.text('some text2', position=pos, arrow_tip=(6, 1), alignment='center',
  430. fontsize=12)
  431. d.set_linewidth(2)
  432. d.arrow(0.25, 0.25, 0.45, 0.45)
  433. d.arrow(0.25, 0.25, 0.25, 4, style='<->')
  434. d.arrow2(4.5, 0, 0, 3, style='<->')
  435. x = np.linspace(0, 9, 201)
  436. y = 4.5 + 0.45*np.cos(0.5*np.pi*x)
  437. d.plot_curve(x, y, arrow='end')
  438. d.display()
  439. raw_input()
  440. if __name__ == '__main__':
  441. _test()