Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6956165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T14:49:57+00:00 2026-05-27T14:49:57+00:00

To state it in a general form, I’m looking for a way to join

  • 0

To state it in a general form, I’m looking for a way to join several points with a gradient color line using matplotlib, and I’m not finding it anywhere.
To be more specific, I’m plotting a 2D random walk with a one color line. But, as the points have a relevant sequence, I would like to look at the plot and see where the data has moved. A gradient colored line would do the trick. Or a line with gradually changing transparency.

I’m just trying to improve the vizualization of my data. Check out this beautiful image produced by the ggplot2 package of R. I’m looking for the same in matplotlib. Thanks.

enter image description here

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T14:49:58+00:00Added an answer on May 27, 2026 at 2:49 pm

    I recently answered a question with a similar request ( creating over 20 unique legend colors using matplotlib ). There I showed that you can map the cycle of colors you need to plot your lines to a color map. You can use the same procedure to get a specific color for each pair of points.

    You should choose the color map carefully, because color transitions along your line might appear drastic if the color map is colorful.

    Alternatively, you can change the alpha of each line segment, ranging from 0 to 1.

    Included in the code example below is a routine (highResPoints) to expand the number of points your random walk has, because if you have too few points, the transitions may seem drastic. This bit of code was inspired by another recent answer I provided: https://stackoverflow.com/a/8253729/717357

    import numpy as np
    import matplotlib.pyplot as plt
    
    def highResPoints(x,y,factor=10):
        '''
        Take points listed in two vectors and return them at a higher
        resultion. Create at least factor*len(x) new points that include the
        original points and those spaced in between.
    
        Returns new x and y arrays as a tuple (x,y).
        '''
    
        # r is the distance spanned between pairs of points
        r = [0]
        for i in range(1,len(x)):
            dx = x[i]-x[i-1]
            dy = y[i]-y[i-1]
            r.append(np.sqrt(dx*dx+dy*dy))
        r = np.array(r)
    
        # rtot is a cumulative sum of r, it's used to save time
        rtot = []
        for i in range(len(r)):
            rtot.append(r[0:i].sum())
        rtot.append(r.sum())
    
        dr = rtot[-1]/(NPOINTS*RESFACT-1)
        xmod=[x[0]]
        ymod=[y[0]]
        rPos = 0 # current point on walk along data
        rcount = 1 
        while rPos < r.sum():
            x1,x2 = x[rcount-1],x[rcount]
            y1,y2 = y[rcount-1],y[rcount]
            dpos = rPos-rtot[rcount] 
            theta = np.arctan2((x2-x1),(y2-y1))
            rx = np.sin(theta)*dpos+x1
            ry = np.cos(theta)*dpos+y1
            xmod.append(rx)
            ymod.append(ry)
            rPos+=dr
            while rPos > rtot[rcount+1]:
                rPos = rtot[rcount+1]
                rcount+=1
                if rcount>rtot[-1]:
                    break
    
        return xmod,ymod
    
    
    #CONSTANTS
    NPOINTS = 10
    COLOR='blue'
    RESFACT=10
    MAP='winter' # choose carefully, or color transitions will not appear smoooth
    
    # create random data
    np.random.seed(101)
    x = np.random.rand(NPOINTS)
    y = np.random.rand(NPOINTS)
    
    fig = plt.figure()
    ax1 = fig.add_subplot(221) # regular resolution color map
    ax2 = fig.add_subplot(222) # regular resolution alpha
    ax3 = fig.add_subplot(223) # high resolution color map
    ax4 = fig.add_subplot(224) # high resolution alpha
    
    # Choose a color map, loop through the colors, and assign them to the color 
    # cycle. You need NPOINTS-1 colors, because you'll plot that many lines 
    # between pairs. In other words, your line is not cyclic, so there's 
    # no line from end to beginning
    cm = plt.get_cmap(MAP)
    ax1.set_color_cycle([cm(1.*i/(NPOINTS-1)) for i in range(NPOINTS-1)])
    for i in range(NPOINTS-1):
        ax1.plot(x[i:i+2],y[i:i+2])
    
    
    ax1.text(.05,1.05,'Reg. Res - Color Map')
    ax1.set_ylim(0,1.2)
    
    # same approach, but fixed color and 
    # alpha is scale from 0 to 1 in NPOINTS steps
    for i in range(NPOINTS-1):
        ax2.plot(x[i:i+2],y[i:i+2],alpha=float(i)/(NPOINTS-1),color=COLOR)
    
    ax2.text(.05,1.05,'Reg. Res - alpha')
    ax2.set_ylim(0,1.2)
    
    # get higher resolution data
    xHiRes,yHiRes = highResPoints(x,y,RESFACT)
    npointsHiRes = len(xHiRes)
    
    cm = plt.get_cmap(MAP)
    
    ax3.set_color_cycle([cm(1.*i/(npointsHiRes-1)) 
                         for i in range(npointsHiRes-1)])
    
    
    for i in range(npointsHiRes-1):
        ax3.plot(xHiRes[i:i+2],yHiRes[i:i+2])
    
    ax3.text(.05,1.05,'Hi Res - Color Map')
    ax3.set_ylim(0,1.2)
    
    for i in range(npointsHiRes-1):
        ax4.plot(xHiRes[i:i+2],yHiRes[i:i+2],
                 alpha=float(i)/(npointsHiRes-1),
                 color=COLOR)
    ax4.text(.05,1.05,'High Res - alpha')
    ax4.set_ylim(0,1.2)
    
    
    
    fig.savefig('gradColorLine.png')
    plt.show()
    

    This figure shows the four cases:

    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

.NET Programming guidelines state that we should not catch general exceptions. I assume the
In @mmalc's response to this question he states that In general you should not
My view-state to action-state transition does not appear to be happening. In the following
Using in-process session state is evil when it comes to scaling web applications (does
This is general programming, but if it makes a difference, I'm using objective-c. Suppose
I'm using jquery tabify with 4 tabs and each content same form calling via
The state monad interface class MonadState s m where get :: m s put
Our state government has opened its transport timetable data. The data is in xml
Is it at the state where it is actually useful and can do more
I need to determine state of last build (success/failure) and I do it like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.