Guest User

Untitled

a guest
Mar 19th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.29 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. def highResPoints(x,y,factor=10):
  5. '''
  6. Take points listed in two vectors and return them at a higher
  7. resultion. Create at least factor*len(x) new points that include the
  8. original points and those spaced in between.
  9.  
  10. Returns new x and y arrays as a tuple (x,y).
  11. '''
  12.  
  13. # r is the distance spanned between pairs of points
  14. r = [0]
  15. for i in range(1,len(x)):
  16. dx = x[i]-x[i-1]
  17. dy = y[i]-y[i-1]
  18. r.append(np.sqrt(dx*dx+dy*dy))
  19. r = np.array(r)
  20.  
  21. # rtot is a cumulative sum of r, it's used to save time
  22. rtot = []
  23. for i in range(len(r)):
  24. rtot.append(r[0:i].sum())
  25. rtot.append(r.sum())
  26.  
  27. dr = rtot[-1]/(NPOINTS*RESFACT-1)
  28. xmod=[x[0]]
  29. ymod=[y[0]]
  30. rPos = 0 # current point on walk along data
  31. rcount = 1
  32. while rPos < r.sum():
  33. x1,x2 = x[rcount-1],x[rcount]
  34. y1,y2 = y[rcount-1],y[rcount]
  35. dpos = rPos-rtot[rcount]
  36. theta = np.arctan2((x2-x1),(y2-y1))
  37. rx = np.sin(theta)*dpos+x1
  38. ry = np.cos(theta)*dpos+y1
  39. xmod.append(rx)
  40. ymod.append(ry)
  41. rPos+=dr
  42. while rPos > rtot[rcount+1]:
  43. rPos = rtot[rcount+1]
  44. rcount+=1
  45. if rcount>rtot[-1]:
  46. break
  47.  
  48. return xmod,ymod
  49.  
  50.  
  51. #CONSTANTS
  52. NPOINTS = 10
  53. COLOR='blue'
  54. RESFACT=10
  55. MAP='winter' # choose carefully, or color transitions will not appear smoooth
  56.  
  57. # create random data
  58. np.random.seed(101)
  59. x = np.random.rand(NPOINTS)
  60. y = np.random.rand(NPOINTS)
  61.  
  62. fig = plt.figure()
  63. ax1 = fig.add_subplot(221) # regular resolution color map
  64. ax2 = fig.add_subplot(222) # regular resolution alpha
  65. ax3 = fig.add_subplot(223) # high resolution color map
  66. ax4 = fig.add_subplot(224) # high resolution alpha
  67.  
  68. # Choose a color map, loop through the colors, and assign them to the color
  69. # cycle. You need NPOINTS-1 colors, because you'll plot that many lines
  70. # between pairs. In other words, your line is not cyclic, so there's
  71. # no line from end to beginning
  72. cm = plt.get_cmap(MAP)
  73. ax1.set_color_cycle([cm(1.*i/(NPOINTS-1)) for i in range(NPOINTS-1)])
  74. for i in range(NPOINTS-1):
  75. ax1.plot(x[i:i+2],y[i:i+2])
  76.  
  77.  
  78. ax1.text(.05,1.05,'Reg. Res - Color Map')
  79. ax1.set_ylim(0,1.2)
  80.  
  81. # same approach, but fixed color and
  82. # alpha is scale from 0 to 1 in NPOINTS steps
  83. for i in range(NPOINTS-1):
  84. ax2.plot(x[i:i+2],y[i:i+2],alpha=float(i)/(NPOINTS-1),color=COLOR)
  85.  
  86. ax2.text(.05,1.05,'Reg. Res - alpha')
  87. ax2.set_ylim(0,1.2)
  88.  
  89. # get higher resolution data
  90. xHiRes,yHiRes = highResPoints(x,y,RESFACT)
  91. npointsHiRes = len(xHiRes)
  92.  
  93. cm = plt.get_cmap(MAP)
  94.  
  95. ax3.set_color_cycle([cm(1.*i/(npointsHiRes-1))
  96. for i in range(npointsHiRes-1)])
  97.  
  98.  
  99. for i in range(npointsHiRes-1):
  100. ax3.plot(xHiRes[i:i+2],yHiRes[i:i+2])
  101.  
  102. ax3.text(.05,1.05,'Hi Res - Color Map')
  103. ax3.set_ylim(0,1.2)
  104.  
  105. for i in range(npointsHiRes-1):
  106. ax4.plot(xHiRes[i:i+2],yHiRes[i:i+2],
  107. alpha=float(i)/(npointsHiRes-1),
  108. color=COLOR)
  109. ax4.text(.05,1.05,'High Res - alpha')
  110. ax4.set_ylim(0,1.2)
  111.  
  112.  
  113.  
  114. fig.savefig('gradColorLine.png')
  115. plt.show()
  116.  
  117. import matplotlib.pyplot as plt
  118. import numpy as np
  119. import matplotlib.collections as mcoll
  120. import matplotlib.path as mpath
  121.  
  122. def colorline(
  123. x, y, z=None, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0.0, 1.0),
  124. linewidth=3, alpha=1.0):
  125. """
  126. http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
  127. http://matplotlib.org/examples/pylab_examples/multicolored_line.html
  128. Plot a colored line with coordinates x and y
  129. Optionally specify colors in the array z
  130. Optionally specify a colormap, a norm function and a line width
  131. """
  132.  
  133. # Default colors equally spaced on [0,1]:
  134. if z is None:
  135. z = np.linspace(0.0, 1.0, len(x))
  136.  
  137. # Special case if a single number:
  138. if not hasattr(z, "__iter__"): # to check for numerical input -- this is a hack
  139. z = np.array([z])
  140.  
  141. z = np.asarray(z)
  142.  
  143. segments = make_segments(x, y)
  144. lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,
  145. linewidth=linewidth, alpha=alpha)
  146.  
  147. ax = plt.gca()
  148. ax.add_collection(lc)
  149.  
  150. return lc
  151.  
  152.  
  153. def make_segments(x, y):
  154. """
  155. Create list of line segments from x and y coordinates, in the correct format
  156. for LineCollection: an array of the form numlines x (points per line) x 2 (x
  157. and y) array
  158. """
  159.  
  160. points = np.array([x, y]).T.reshape(-1, 1, 2)
  161. segments = np.concatenate([points[:-1], points[1:]], axis=1)
  162. return segments
  163.  
  164. N = 10
  165. np.random.seed(101)
  166. x = np.random.rand(N)
  167. y = np.random.rand(N)
  168. fig, ax = plt.subplots()
  169.  
  170. path = mpath.Path(np.column_stack([x, y]))
  171. verts = path.interpolated(steps=3).vertices
  172. x, y = verts[:, 0], verts[:, 1]
  173. z = np.linspace(0, 1, len(x))
  174. colorline(x, y, z, cmap=plt.get_cmap('jet'), linewidth=2)
  175.  
  176. plt.show()
  177.  
  178. # Setup
  179. x = np.linspace(0,4*np.pi,1000)
  180. y = np.sin(x)
  181. MAP = 'cubehelix'
  182. NPOINTS = len(x)
  183.  
  184. %%timeit -n1 -r1
  185. # Using IPython notebook timing magics
  186. fig = plt.figure()
  187. ax1 = fig.add_subplot(111) # regular resolution color map
  188. cm = plt.get_cmap(MAP)
  189. for i in range(10):
  190. ax1.set_color_cycle([cm(1.*i/(NPOINTS-1)) for i in range(NPOINTS-1)])
  191. for i in range(NPOINTS-1):
  192. plt.plot(x[i:i+2],y[i:i+2])
  193.  
  194. %%timeit -n1 -r1
  195. fig = plt.figure()
  196. ax1 = fig.add_subplot(111) # regular resolution color map
  197. for i in range(10):
  198. colorline(x,y,cmap='cubehelix', linewidth=1)
  199.  
  200. import numpy as np
  201. import matplotlib.pyplot as plt
  202.  
  203. def colored_line(x, y, z=None, linewidth=1, MAP='jet'):
  204. # this uses pcolormesh to make interpolated rectangles
  205. xl = len(x)
  206. [xs, ys, zs] = [np.zeros((xl,2)), np.zeros((xl,2)), np.zeros((xl,2))]
  207.  
  208. # z is the line length drawn or a list of vals to be plotted
  209. if z == None:
  210. z = [0]
  211.  
  212. for i in range(xl-1):
  213. # make a vector to thicken our line points
  214. dx = x[i+1]-x[i]
  215. dy = y[i+1]-y[i]
  216. perp = np.array( [-dy, dx] )
  217. unit_perp = (perp/np.linalg.norm(perp))*linewidth
  218.  
  219. # need to make 4 points for quadrilateral
  220. xs[i] = [x[i], x[i] + unit_perp[0] ]
  221. ys[i] = [y[i], y[i] + unit_perp[1] ]
  222. xs[i+1] = [x[i+1], x[i+1] + unit_perp[0] ]
  223. ys[i+1] = [y[i+1], y[i+1] + unit_perp[1] ]
  224.  
  225. if len(z) == i+1:
  226. z.append(z[-1] + (dx**2+dy**2)**0.5)
  227. # set z values
  228. zs[i] = [z[i], z[i] ]
  229. zs[i+1] = [z[i+1], z[i+1] ]
  230.  
  231. fig, ax = plt.subplots()
  232. cm = plt.get_cmap(MAP)
  233. ax.pcolormesh(xs, ys, zs, shading='gouraud', cmap=cm)
  234. plt.axis('scaled')
  235. plt.show()
  236.  
  237. # create random data
  238. N = 10
  239. np.random.seed(101)
  240. x = np.random.rand(N)
  241. y = np.random.rand(N)
  242. colored_line(x, y, linewidth = .01)
  243.  
  244. import numpy as np
  245. import matplotlib.pyplot as plt
  246. from matplotlib import cm
  247. import matplotlib.collections as mcoll
  248. import matplotlib.path as mpath
  249.  
  250. x = np.arange(-8, 4, 0.01)
  251. y = 1 + 0.5 * x**2
  252.  
  253. MAP = 'jet'
  254. NPOINTS = len(x)
  255.  
  256. fig = plt.figure()
  257. ax1 = fig.add_subplot(111)
  258. cm = plt.get_cmap(MAP)
  259. for i in range(10):
  260. ax1.set_color_cycle([cm(1.0*i/(NPOINTS-1)) for i in range(NPOINTS-1)])
  261. for i in range(NPOINTS-1):
  262. plt.plot(x[i:i+2],y[i:i+2])
  263.  
  264. plt.title('Inner minimization', fontsize=25)
  265. plt.xlabel(r'Friction torque $[Nm]$', fontsize=25)
  266. plt.ylabel(r'Accelerations energy $[frac{Nm}{s^2}]$', fontsize=25)[enter image description here][1]
  267. plt.show() # Show the figure
Add Comment
Please, Sign In to add comment