MatplotlibDraw.py 14 KB

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