Search code examples
matplotlibseabornscatter-plot

Warping Matplotlib/Seaborn Scatter Plot into Parallelogram


I have a 2D scatterplot (in either matplotlib or seaborn) and an angle e.g. 64 degrees. I want to plot a warped version of this scatter plot where the x-axis of the first plot is held fixed but the second axis is warped such that the y-axis of the first plot is now at the given angle with the x-axis of the new plot (i.e. 64 degrees). How can I do this?

In other words, I want to take the original scatter plot and "push" the y-axis to the right to form a parallelogram-like plot where the angle between the old y axis and the old/new x-axis is the given angle.


Solution

  • Here is an adaption of an old tutorial example:

    import matplotlib.pyplot as plt
    from matplotlib.transforms import Affine2D
    import mpl_toolkits.axisartist.floating_axes as floating_axes
    import numpy as np
    
    fig = plt.figure()
    skewed_transform = Affine2D().skew_deg(90 - 64, 0)
    grid_helper = floating_axes.GridHelperCurveLinear(skewed_transform, extremes=(-0.5, 1.5, -0.5, 1.5))
    skewed_ax = floating_axes.FloatingSubplot(fig, 111, grid_helper=grid_helper)
    skewed_ax.set_facecolor('0.95')  # light grey background
    skewed_ax.axis["top"].set_visible(False)
    skewed_ax.axis["right"].set_visible(False)
    fig.add_subplot(skewed_ax)
    x, y = np.random.rand(2, 100)  # random point in a square of [0,1]x[0,1]
    skewed_ax.scatter(x, y, transform=skewed_transform + skewed_ax.transData)
    plt.show()
    

    skewed ax