0

To clarify, I have reviewed similar questions that were answered, such as this and this. However, these solutions seem to only work for lines that are composed of multiple points. In my case, I am wondering if this can be applied or if there's another way to do this for lines given two pairs of x,y coordinates. I am looking to create a gradient line between the two points in matplotlib in order to express directionality. A snippet of my code looks like this:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,14))
ax = plt.gca()

for coord in coords:
     #coord is represented as [(x1,y1), (x2,y2)]
     xcoords = [loc[0] for loc in coord]
     ycoords = [loc[1] for loc in coord]
     ax.plot(xcoords, ycoords, '.-', c='w')

Here's a snippit of the plot it produces:

enter image description here

The image it produces is fine, however, I would love to create a black-to-white transition line between the two points in order to express directionality. Any help would be appreciated.

Lukar Huang
  • 77
  • 1
  • 4
  • 1
    To subdivide the line into many segments, you can do `x = np.linspace(xcoords[0], xcoords[-1], 100); y = np.linspace(ycoords[0], ycoords[-1], 100)` and `ax.plot(x, y, ...)` – JohanC Mar 08 '21 at 23:08

1 Answers1

0

You can break a line segment into many smaller segments and increment the alpha as shown for the 3 lines below:

import matplotlib.pyplot as plt
import numpy as np

ALPHA_INCREMENTS = 100
line1 = [(1,1),(5,3)]
line2 = [(3,1),(5,2.8)]
line3 = [(1,3),(5,3.2)]
lines = [line1, line2, line3]

for line in lines:
    x_vals = np.linspace(line[0][0], line[1][0], ALPHA_INCREMENTS)
    y_vals = np.linspace(line[0][1], line[1][1],ALPHA_INCREMENTS)
    alphas = np.linspace(0,1,ALPHA_INCREMENTS)

    for i in range(ALPHA_INCREMENTS-1):
        plt.plot(x_vals[i:i+2], y_vals[i:i+2], color = 'red', alpha = alphas[i])
plt.show()

You can play around with the ALPHA_INCREMENTS constant to make it look good for your particular plot.

enter image description here

pakpe
  • 5,391
  • 2
  • 8
  • 23