MatplotlibDraw.py 15 KB

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