Search code examples
pythonmatplotlibmap-projections

Overlaying straight lines over a Mollweide Projection


I am trying to overlay straight lines connecting points on a Mollweide Projection, instead of curves.

What I am currently getting (top) and the desired plot (bottom):

Mollweide Projection with curved and straight lines

Here is the code that creates the top image:

import matplotlib.pyplot as plt

colorcycle = ["Red", "Black", "Blue", "DarkMagenta", "Magenta", "MidnightBlue", "Orange", "Green", "Pink"]
ra_data = [-2.831704208910444, -0.048424160096582486, -0.4534557382898992, -2.5592914739299166, -1.1679202302277936, -1.0466163565556836, -0.5471537391832145, 2.4131794902699597, 2.945867940612645]
de_data = [-1.5056972910247601, 0.4995935170663689, -0.2603176032642063, -0.523242728430892, -0.8540960680851971, 0.7025543651222854, 0.6495085731664219, 0.004916592502868027, 0.36081889758179575]

fig = plt.figure(figsize=(8, 6), dpi=100)
ax = fig.add_subplot(111, projection="mollweide")
ax.scatter(ra_data, de_data, marker='o', alpha=0.7, color=colorcycle)
ax.plot(ra_data, de_data, color='Blue', alpha=0.5)
ax.grid(True)

plt.show()

Solution

  • You want to transform from data coordinates to axes coordinates (say x and y) and plot the lines telling explicitly to Matplotlib to use the system of coordinates associated with your ax — all this stuff is nicely explained in the Transformations Tutorial.

    import matplotlib.pyplot as plt
    
    colorcycle = ["Red", "Black", "Blue", "DarkMagenta", "Magenta", "MidnightBlue", "Orange", "Green", "Pink"]
    ra_data = [-2.831704208910444, -0.048424160096582486, -0.4534557382898992, -2.5592914739299166, -1.1679202302277936, -1.0466163565556836, -0.5471537391832145, 2.4    131794902699597, 2.945867940612645]
    de_data = [-1.5056972910247601, 0.4995935170663689, -0.2603176032642063, -0.523242728430892, -0.8540960680851971, 0.7025543651222854, 0.6495085731664219, 0.004916    592502868027, 0.36081889758179575]
    
    fig = plt.figure(figsize=(8, 6), dpi=100)
    ax = fig.add_subplot(111, projection="mollweide")
    ax.scatter(ra_data, de_data, marker='o', alpha=0.7, color=colorcycle)
    ax.grid()
    #################################################################
    pos2ax = (ax.transData+ax.transAxes.inverted()).transform
    x, y = zip(*[pos2ax((ra,de)) for ra, de in zip(ra_data,de_data)])
    ax.plot(x, y, transform=ax.transAxes, color='Blue', alpha=0.5)
    #################################################################
    

    enter image description here