Skip to content
Advertisement

Position label of colorbar

I have this function:

def scatter_diagdistance(x, y) :
    z = abs(y-x)
    fig, ax = plt.subplots(dpi=200)
    sc = ax.scatter(x, y, c=z, s=50, edgecolor='none')
    x_diag = np.arange(min(x*100), max(x*100))/100
    ax.plot(x_diag, x_diag, '-', c="red")
    cbar = fig.colorbar(sc)
    cbar.set_label('Distance from diagonal')
    return(fig)

Which gives me this sort of image: figure generated by the code snippet How can I position the “Distance from diagonal” to the left of the colorbar?

(Also, is there a cleaner way to plot the diagonal over a scatter plot like this?)

Advertisement

Answer

one way to do it is to use the text as the label for the secondary y-axis. That will keep the text before the colorbar. Also, you can draw a line for the diagonal. The code (without your data) is shown below. If you use transform=ax.transAxes details, the coordinates are interpreted as axes coordinates

fig, ax = plt.subplots(dpi=200)
ax2 = ax.twinx() ##Create secondary axis
ax2.set_yticks([]) ##No ticks for the secondary axis
sc = ax.scatter(0.5, 0.5, c=1, 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)

Plot

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement