73032

Matplotlib curve with arrow ticks

I was wondering if it is possible to plot a curve in matplotlib with arrow ticks.

Something like:

from pylab import * y = linspace(0,10,0.01) x = cos(y) plot(x, y, '->')

which should come out with a curve made like this --->---->----> when x increases and like this ---<----<----< whenit decreases (and for y as well, of course). EDIT: Furthermore, the arrows should be inclined in the curve's direction (for example, 45 degrees for the y=x function)

Answer1:

It is possible to use the same strategy as in matplotlib streamplot function. Based on the example already given by hitzg:

import numpy as np import matplotlib.pyplot as plt import matplotlib.lines as mlines import matplotlib.patches as mpatches def add_arrow_to_line2D( axes, line, arrow_locs=[0.2, 0.4, 0.6, 0.8], arrowstyle='-|>', arrowsize=1, transform=None): """ Add arrows to a matplotlib.lines.Line2D at selected locations. Parameters: ----------- axes: line: Line2D object as returned by plot command arrow_locs: list of locations where to insert arrows, % of total length arrowstyle: style of the arrow arrowsize: size of the arrow transform: a matplotlib transform instance, default to data coordinates Returns: -------- arrows: list of arrows """ if not isinstance(line, mlines.Line2D): raise ValueError("expected a matplotlib.lines.Line2D object") x, y = line.get_xdata(), line.get_ydata() arrow_kw = { "arrowstyle": arrowstyle, "mutation_scale": 10 * arrowsize, } color = line.get_color() use_multicolor_lines = isinstance(color, np.ndarray) if use_multicolor_lines: raise NotImplementedError("multicolor lines not supported") else: arrow_kw['color'] = color linewidth = line.get_linewidth() if isinstance(linewidth, np.ndarray): raise NotImplementedError("multiwidth lines not supported") else: arrow_kw['linewidth'] = linewidth if transform is None: transform = axes.transData arrows = [] for loc in arrow_locs: s = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2)) n = np.searchsorted(s, s[-1] * loc) arrow_tail = (x[n], y[n]) arrow_head = (np.mean(x[n:n + 2]), np.mean(y[n:n + 2])) p = mpatches.FancyArrowPatch( arrow_tail, arrow_head, transform=transform, **arrow_kw) axes.add_patch(p) arrows.append(p) return arrows y = np.linspace(0, 100, 200) x = np.cos(y/5.) fig, ax = plt.subplots(1, 1) # print the line and the markers in seperate steps line, = ax.plot(x, y, 'k-') add_arrow_to_line2D(ax, line, arrow_locs=np.linspace(0., 1., 200), arrowstyle='->') plt.show()

<img src=https://www.e-learn.cn/content/wangluowenzhang/"https://i.stack.imgur.com/r15M2.png" alt="enter image description here">

Also refer to this answer.

Answer2:

Try this:

import numpy as np import matplotlib.pyplot as plt y = np.linspace(0,100,100) x = np.cos(y/5.) # use masked arrays x1 = np.ma.masked_array(x[:-1], np.diff(x)>=0) x2 = np.ma.masked_array(x[:-1], np.diff(x)<=0) # print the line and the markers in seperate steps plt.plot(x, y, 'k-') plt.plot(x1, y[:-1], 'k<') plt.plot(x2, y[:-1], 'k>') plt.show()

<img src=https://www.e-learn.cn/content/wangluowenzhang/"https://i.stack.imgur.com/LnbYB.png" alt="Line with arrows">

Recommend

  • Oracle Forms 6i crashes with 0xC0000005 at start after installing patch 19 [closed]
  • How to show matplotlib plot in one window
  • Search mercurial repository for changes in a certain path
  • How to setup a slider for pen size into the code in Netlogo
  • Plot points linked with edges using gnuplot
  • Changing Node ID with every Setup in Netlogo
  • Dynamic patching of databases
  • When using null layout in Swing, my components don't appear until I hover on them
  • osx: vim visual cut and paste leaves whitespace, overwrites
  • How to use BigCartel “Variables” to Call Different Product Categories
  • Angular2 patchValue push value into array
  • NetLogo: Model gets stuck w no error mesage
  • How to control square size in a grid from square area?
  • Can't compile / install Ruby 1.8.6 with RVM (Error running '__rvm_make -B -j8')
  • Who gets credit for a hand-edited patch file?
  • Matplotlib curve with arrow ticks
  • Can't get JSON data from Rails API
  • git fork repo to same organization
  • horizontal-vertical only lines
  • Difference between a changeset and a patch?
  • Zipfile python module bytesize difference
  • The required anti-forgery cookie “__RequestVerificationToken” is not present. MVC 5
  • PySpark Yarn Application fails on groupBy
  • Spark dataframe to nested map
  • Convert adjacency matrix to a csv file
  • XGBOOST - DMATRIX
  • Implicit property animations do not work with CAReplicatorLayer?
  • Change the width of the JQM panels
  • Weird LEFT OUTER JOIN on Includes eager loading of rails 3
  • What's a fast (non-loop) way to apply a dict to a ndarray (meaning use elements as keys and rep
  • Transpose table then set and rename index
  • iOS - MKOverlayView custom view rect fills works, but line draws do not
  • What do I do with this error when I run tests in rails?
  • Selectively hide background elements when overlayed with transparent div
  • Dynamically load css stylesheet and wait for it to load
  • Calculating ratio of reciprocated ties for each node in igraph
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • Mysterious problem with floating point in LISP - time axis generation
  • Uncaught Error: Could not find module `ember-load-initializers`
  • Array.prototype.includes - not transformed with babel