Skip to content

Colorbar label position different when executing a block of code #6471

@saintsfan342000

Description

@saintsfan342000

Matplotlib version 1.5.1
Python 3.4.4 on Windows via Anaconda 2.2.0 (64-bit)
Also occured on a Python 3.5.1 install on Lubuntu via Anaconda 4.0
Jupyter QtConsole 4.1.0; IPython verion 4.0.0

I made some functions for positioning and formatting x and y labels and to draw arrows pointing towards these labels. Today I wrote a function that similarly formats the colorbar label. However, the behavior is erroneous if the function is called within a block of code or in a script executed on the command line. I defined a condensed version of the function here as mycolorbar().

If I run the following in a script from the command line, or if I paste everything into a single code block in the Jupyter QtConsole, I get the figure shown below the code. In the QtConsole this occurs regardless of whether I've called %matplotlib

import matplotlib.pyplot as plt
import numpy as np

def mycolorbar(ax,cbar):
    fig = ax.get_figure()
    cax = cbar.ax
    inv = ax.transAxes.inverted()
    R = fig.canvas.get_renderer()
    caxY = cax.yaxis
    ylab = caxY.get_label()
    ticklabelbbox = inv.transform( caxY.get_ticklabel_extents(R)[1].get_points() )
    ylab.set_verticalalignment('center')
    ylab.set_horizontalalignment('center')
    ylab.set_rotation(0)
    xpos, ypos = np.max(ticklabelbbox[:,0]), (3/4)
    caxY.set_label_coords( xpos , ypos , transform = ax.transAxes )

x,y,z = [np.random.rand(1000) for i in range(3)]

fig = plt.figure(facecolor='w')
ax = fig.add_axes([.1,.1,.8,.8])
plt.tricontourf(x,y,z)
plt.xlabel('xlab')
plt.ylabel('ylab')
cbar = plt.colorbar(label='clab')
mycolorbar( ax, cbar)
plt.show()

farout

Observe how far out to the right the colorbar label are. This is "incorrect".

Now, when working interactively in the QtConsole, if I run all of the above code _except_ the last line, let the figure window render, then execute that last line mycolorbar( ax, cbar) on its own, I get the "correct" position for the colorbar label.

closein

I'm asking anyone to debug my code. Just trying to bring a potential issue to light. Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions