Python matplotlib colorbar axis offset string position/location
I want to make a contour-plot with a horizontal colorbar. The bar should have labels with scientific notation. Everything goes well in the code below. However, now I want to change the position of the multiplicator specifying the scientific scale. I think this is called an offset string by the axis. Does anybody know how to do this? I want to place the multiplicator right 开发者_如何学JAVAof the colorbar (as if it would be an additional label).
#http://matplotlib.sourceforge.net/examples/pylab_examples/griddata_demo.html
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
from matplotlib import rcParams
from matplotlib import rc
# make up data.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# grid the data.
zi = griddata(x,y,z,xi,yi,interp='linear')
rcParams['axes.formatter.limits'] = (-1,1)
plt.figure()
CS = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar(orientation='horizontal') # draw colorbar
# plot data points.
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()
From your code above, just use:
bar.ax.xaxis.get_offset_text().set_position((x,y))
where (x,y)
is the location where you want the text in axes coordinates (e.g. x=0
is the left hand side and x=1
is the right hand side).
Also note that setting the y-coordinate won't do anything in this case, as the location in the y-direction is controlled by the axis padding, etc. (You can change it, but it's slightly more complicated.)
I found that that command lets you directly work on the label position.
bar.ax.yaxis.set_label_coords(3, .5)
It took me some iterations to position text correctly, since I found working colorbar coordinates completely unintuitive.
Following the suggestion from Joe Kington above, I found the following modification most easy:
bar.ax.yaxis.set_label_position('right')
bar.ax.set_ylabel('YourLabel', rotation='horizontal')
精彩评论