MatplotlibDraw.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import os
  2. import matplotlib
  3. matplotlib.use('TkAgg')
  4. import matplotlib.pyplot as mpl
  5. import numpy as np
  6. class MatplotlibDraw:
  7. line_colors = {'red': 'r', 'green': 'g', 'blue': 'b', 'cyan': 'c',
  8. 'magenta': 'm', 'purple': 'p',
  9. 'yellow': 'y', 'black': 'k', 'white': 'w', '': ''}
  10. def __init__(self):
  11. self.instruction_file = None
  12. def set_instruction_file(self, filename='tmp_mpl.py'):
  13. """
  14. instruction_file: name of file where all the instructions
  15. are recorded.
  16. """
  17. if filename:
  18. self.instruction_file = open(self.instruction_file, 'w')
  19. else:
  20. self.instruction_file = None
  21. def set_coordinate_system(self, xmin, xmax, ymin, ymax, axis=False):
  22. """
  23. Define the drawing area [xmin,xmax]x[ymin,ymax].
  24. axis: None or False means that axes with tickmarks
  25. are not drawn.
  26. """
  27. self.mpl = mpl
  28. self.xmin, self.xmax, self.ymin, self.ymax = \
  29. float(xmin), float(xmax), float(ymin), float(ymax)
  30. self.xrange = self.xmax - self.xmin
  31. self.yrange = self.ymax - self.ymin
  32. self.axis = axis
  33. # Compute the right X11 geometry on the screen based on the
  34. # x-y ratio of axis ranges
  35. ratio = (self.ymax-self.ymin)/(self.xmax-self.xmin)
  36. self.xsize = 800 # pixel size
  37. self.ysize = self.xsize*ratio
  38. geometry = '%dx%d' % (self.xsize, self.ysize)
  39. # See http://stackoverflow.com/questions/7449585/how-do-you-set-the-absolute-position-of-figure-windows-with-matplotlib
  40. self.mpl.ion() # important for interactive drawing and animation
  41. if self.instruction_file is not None:
  42. self.instruction_file.write("""\
  43. import matplotlib.pyplot as mpl
  44. mpl.ion() # for interactive drawing
  45. """)
  46. self._make_axes(new_figure=True)
  47. manager = self.mpl.get_current_fig_manager()
  48. manager.window.wm_geometry(geometry)
  49. self.set_linecolor('red')
  50. self.set_linewidth(2)
  51. self.set_linestyle('solid')
  52. self.set_filled_curves()
  53. def _make_axes(self, new_figure=False):
  54. if new_figure:
  55. self.fig = self.mpl.figure()
  56. self.ax = self.fig.gca()
  57. self.ax.set_xlim(self.xmin, self.xmax)
  58. self.ax.set_ylim(self.ymin, self.ymax)
  59. self.ax.set_aspect('equal') # extent of 1 unit is the same on the axes
  60. if not self.axis:
  61. self.mpl.axis('off')
  62. axis_cmd = "mpl.axis('off') # do not show axes with tickmarks\n"
  63. else:
  64. axis_cmd = ''
  65. if self.instruction_file is not None:
  66. fig = 'fig = mpl.figure()\n' if new_figure else ''
  67. self.instruction_file.write("""\
  68. %s
  69. ax = fig.gca()
  70. xmin, xmax, ymin, ymax = %s, %s, %s, %s
  71. ax.set_xlim(xmin, xmax)
  72. ax.set_ylim(ymin, ymax)
  73. ax.set_aspect('equal')
  74. %s
  75. """ % (fig, self.xmin, self.xmax, self.ymin, self.ymax, axis_cmd))
  76. def set_linecolor(self, color):
  77. """Change the color of lines."""
  78. self.linecolor = MatplotlibDraw.line_colors[color]
  79. def set_linestyle(self, style):
  80. """Change line style: 'solid', 'dashed', 'dashdot', 'dotted'."""
  81. if not style in ('solid', 'dashed', 'dashdot', 'dotted'):
  82. raise ValueError('Illegal line style: %s' % style)
  83. self.linestyle = style
  84. def set_linewidth(self, width):
  85. """Change the line width (int, starts at 1)."""
  86. self.linewidth = width
  87. def set_filled_curves(self, color='', pattern=''):
  88. """Fill area inside curves with current line color."""
  89. if color is False:
  90. self.fillcolor = ''
  91. self.fillpattern = ''
  92. else:
  93. self.fillcolor = color if len(color) == 1 else \
  94. MatplotlibDraw.line_colors[color]
  95. self.fillpattern = pattern
  96. def set_grid(self, on=False):
  97. self.mpl.grid(on)
  98. if self.instruction_file is not None:
  99. self.instruction_file.write("\nmpl.grid(%s)\n" % str(on))
  100. def erase(self):
  101. """Erase the current figure."""
  102. self.mpl.delaxes()
  103. if self.instruction_file is not None:
  104. self.instruction_file.write("\nmpl.delaxes() # erase\n")
  105. self._make_axes(new_figure=False)
  106. def define_curve(self, x, y,
  107. linestyle=None, linewidth=None,
  108. linecolor=None, arrow=None,
  109. fillcolor=None, fillpattern=None):
  110. """Define a curve with coordinates x and y (arrays)."""
  111. self.xdata = np.asarray(x, dtype=np.float)
  112. self.ydata = np.asarray(y, dtype=np.float)
  113. if linestyle is None:
  114. # use "global" linestyle
  115. linestyle = self.linestyle
  116. if linecolor is None:
  117. linecolor = self.linecolor
  118. if linewidth is None:
  119. linewidth = self.linewidth
  120. if fillcolor is None:
  121. fillcolor = self.fillcolor
  122. if fillpattern is None:
  123. fillpattern = self.fillpattern
  124. if self.instruction_file is not None:
  125. import pprint
  126. self.instruction_file.write('x = %s\n' % \
  127. pprint.pformat(self.xdata.tolist()))
  128. self.instruction_file.write('y = %s\n' % \
  129. pprint.pformat(self.ydata.tolist()))
  130. if fillcolor or fillpattern:
  131. if fillpattern != '':
  132. fillcolor = 'white'
  133. #print '%d coords, fillcolor="%s" linecolor="%s" fillpattern="%s"' % (x.size, fillcolor, linecolor, fillpattern)
  134. self.ax.fill(x, y, fillcolor, edgecolor=linecolor,
  135. linewidth=linewidth, hatch=fillpattern)
  136. if self.instruction_file is not None:
  137. self.instruction_file.write("ax.fill(x, y, '%s', edgecolor='%s', linewidth=%d, hatch='%s')\n" % (fillcolor, linecolor, linewidth, fillpattern))
  138. else:
  139. self.ax.plot(x, y, linecolor, linewidth=linewidth,
  140. linestyle=linestyle)
  141. if self.instruction_file is not None:
  142. self.instruction_file.write("ax.plot(x, y, '%s', linewidth=%d, linestyle='%s')\n" % (linecolor, linewidth, linestyle))
  143. if arrow:
  144. if not arrow in ('start', 'end', 'both'):
  145. raise ValueError("arrow argument must be 'start', 'end', or 'both', not %s" % repr(arrow))
  146. # Add arrow to first and/or last segment
  147. start = arrow == 'start' or arrow == 'both'
  148. end = arrow == 'end' or arrow == 'both'
  149. if start:
  150. x_s, y_s = x[1], y[1]
  151. dx_s, dy_s = x[0]-x[1], y[0]-y[1]
  152. self.arrow(x_s, y_s, dx_s, dy_s)
  153. if end:
  154. x_e, y_e = x[-2], y[-2]
  155. dx_e, dy_e = x[-1]-x[-2], y[-1]-y[-2]
  156. self.arrow(x_e, y_e, dx_e, dy_e)
  157. def display(self):
  158. """Display the figure. Last possible command."""
  159. self.mpl.draw()
  160. if self.instruction_file is not None:
  161. self.instruction_file.write('mpl.draw()\n')
  162. def savefig(self, filename):
  163. """Save figure in file."""
  164. self.mpl.savefig(filename)
  165. if self.instruction_file is not None:
  166. self.instruction_file.write('mpl.savefig(%s)\n' % filename)
  167. def text(self, text, position, alignment='center', fontsize=18,
  168. arrow_tip=None):
  169. """
  170. Write text at a position (centered, left, right - according
  171. to the alignment string). position is a 2-tuple.
  172. arrow+tip != None draws an arrow from the text to a point
  173. (on a curve, for instance). The arrow_tip argument is then
  174. the (x,y) coordinates for the arrow tip.
  175. """
  176. x, y = position
  177. if arrow_tip is None:
  178. self.ax.text(x, y, text, horizontalalignment=alignment,
  179. fontsize=fontsize)
  180. if self.instruction_file is not None:
  181. self.instruction_file.write("""\
  182. ax.text(%g, %g, %s,
  183. horizontalalignment=%s, fontsize=%d)
  184. """ % (x, y, repr(text), repr(alignment), fontsize))
  185. else:
  186. if not len(arrow_tip) == 2:
  187. raise ValueError('arrow_tip=%s must be (x,y) pt.' % arrow)
  188. pt = arrow_tip
  189. self.ax.annotate(text, xy=pt, xycoords='data',
  190. textcoords='data', xytext=position,
  191. horizontalalignment=alignment,
  192. verticalalignment='top',
  193. fontsize=fontsize,
  194. arrowprops=dict(arrowstyle='->',
  195. facecolor='black',
  196. #linewidth=2,
  197. linewidth=1,
  198. shrinkA=5,
  199. shrinkB=5))
  200. if self.instruction_file is not None:
  201. self.instruction_file.write("""\
  202. ax.annotate('%s', xy=%s, xycoords='data',
  203. textcoords='data', xytext=%s,
  204. horizontalalignment='%s',
  205. verticalalignment='top',
  206. fontsize=%d,
  207. arrowprops=dict(arrowstyle='->',
  208. facecolor='black',
  209. linewidth=2,
  210. shrinkA=5,
  211. shrinkB=5))
  212. """ % (text, pt, position, alignment, fontsize))
  213. # Drawing annotations with arrows:
  214. #http://matplotlib.sourceforge.net/users/annotations_intro.html
  215. #http://matplotlib.sourceforge.net/mpl_examples/pylab_examples/annotation_demo2.py
  216. #http://matplotlib.sourceforge.net/users/annotations_intro.html
  217. #http://matplotlib.sourceforge.net/users/annotations_guide.html#plotting-guide-annotation
  218. def arrow(self, x, y, dx, dy, style='->',
  219. linestyle=None, linewidth=None, linecolor=None):
  220. """Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'."""
  221. if linestyle is None:
  222. # use "global" linestyle
  223. linestyle = self.linestyle
  224. if linecolor is None:
  225. linecolor = self.linecolor
  226. if linewidth is None:
  227. linewidth = self.linewidth
  228. if style == '->' or style == '<->':
  229. self.mpl.arrow(x, y, dx, dy, hold=True,
  230. facecolor=linecolor,
  231. edgecolor=linecolor,
  232. linewidth=linewidth,
  233. head_width=0.1,
  234. #width=1,
  235. length_includes_head=True,
  236. shape='full')
  237. if self.instruction_file is not None:
  238. self.instruction_file.write("""\
  239. mpl.arrow(x=%g, y=%g, dx=%g, dy=%g,
  240. facecolor='%s', edgecolor='%s',
  241. linewidth=%g, head_width=0.1,
  242. length_includes_head=True,
  243. shape='full')
  244. """ % (x, y, dx, dy, linecolor, linecolor, linewidth))
  245. if style == '<-' or style == '<->':
  246. self.mpl.arrow(x+dx, y+dy, -dx, -dy, hold=True,
  247. facecolor=linecolor,
  248. edgecolor=linecolor,
  249. linewidth=linewidth,
  250. head_width=0.1,
  251. #width=1,
  252. length_includes_head=True,
  253. shape='full')
  254. if self.instruction_file is not None:
  255. self.instruction_file.write("""\
  256. mpl.arrow(x=%g, y=%g, dx=%g, dy=%g,
  257. facecolor='%s', edgecolor='%s',
  258. linewidth=%g, head_width=0.1,
  259. length_includes_head=True,
  260. shape='full')
  261. """ % (x+dx, y+dy, -dx, -dy, linecolor, linecolor, linewidth))
  262. def arrow2(self, x, y, dx, dy, style='->'):
  263. """Draw arrow (dx,dy) at (x,y). `style` is '->', '<-' or '<->'."""
  264. self.ax.annotate('', xy=(x+dx,y+dy) , xytext=(x,y),
  265. arrowprops=dict(arrowstyle=style,
  266. facecolor='black',
  267. linewidth=1,
  268. shrinkA=0,
  269. shrinkB=0))
  270. if self.instruction_file is not None:
  271. self.instruction_file.write("")
  272. def _test():
  273. d = MatplotlibDraw(0, 10, 0, 5, instruction_file='tmp3.py', axis=True)
  274. d.set_linecolor('magenta')
  275. d.set_linewidth(6)
  276. # triangle
  277. x = np.array([1, 4, 1, 1]); y = np.array([1, 1, 4, 1])
  278. d.set_filled_curves('magenta')
  279. d.define_curve(x, y)
  280. d.set_filled_curves(False)
  281. d.define_curve(x+4, y)
  282. d.text('some text1', position=(8,4), arrow_tip=(6, 1), alignment='left',
  283. fontsize=18)
  284. pos = np.array((7,4.5)) # numpy points work fine
  285. d.text('some text2', position=pos, arrow_tip=(6, 1), alignment='center',
  286. fontsize=12)
  287. d.set_linewidth(2)
  288. d.arrow(0.25, 0.25, 0.45, 0.45)
  289. d.arrow(0.25, 0.25, 0.25, 4, style='<->')
  290. d.arrow2(4.5, 0, 0, 3, style='<->')
  291. x = np.linspace(0, 9, 201)
  292. y = 4.5 + 0.45*np.cos(0.5*np.pi*x)
  293. d.define_curve(x, y, arrow='end')
  294. d.display()
  295. raw_input()
  296. if __name__ == '__main__':
  297. _test()