Search code examples
pythonmatplotlibcolorscolorbar

Scale colour over multiple graphs


I have this function that plots data along two axes, and colours them according to their distance to the diagonal:

def scatter_diagdistance(x, y) :
    z = abs(y-x)
    fig, ax = plt.subplots(dpi=200)
    ax2 = ax.twinx() ##Create secondary axis
    ax2.set_yticks([]) ##No ticks for the secondary axis
    sc = ax.scatter(x, y, c=z, s=50, edgecolor='none')
    ax2.set_ylabel('Distance from diagonal') ##Label for secondary axis
    ax.plot([0, 1], [0, 1], '-', c="red", transform=ax.transAxes) #Line from 0 to 1
    cbar = fig.colorbar(sc)
    ax.set_xlabel('Ref mutation frequencies')
    ax.set_ylabel('Decoded mutation frequencies')
    return fig, z

The figures it creates look like this:

scatter plot created by the above code

For the next part of my project, I'd like to compare these graphs between a few different setups. I'd like to use the same colour scale for the whole multi-panel figure, so as to show that one method sticks closer to the diagonal than others. I'd also like the associated colour bar, which doesn't need to be included in the figure output, as I'll be editing the panels together afterwards.

How do I combine all the z values together, establish a colour scale based on that, then separate them back again for each plot?


Solution

  • From all data calculate the maximum distance to diagonal.

    Pass this maxDist as parameter to scatter_diagdistance

    Use it in arguments vmin and vmax for scatter plot call. It will be used in the normalize function instead of the local max in the z array.

    def scatter_diagdistance(x, y, maxDist):
        # ...
        sc = ax.scatter(x, y, c=z, s=50, edgecolor='none', vmin=0, vmax=maxDist)
        # ...
    

    Your distance calculation is wrong.

    Point (1.0,0) has a distance of 0.5*sqrt(2) to the diagonal not 1.0


    Your diagonal line is wrong. Draw the grid to see the problem.

    It does not pass through (1,1).

    It is drawn from corner to corner. In your figure that is (1.1,1.3)

    Most likely also not passing (0,0)