Matplotlib: contour plot with slider widget - python

Newbie matplotlib user here. I'm trying to use a slider to adjust a parameter in a contour plot, but when I do so, I get:
AttributeError: QuadContourSet instance has no attribute 'set_data'
I suspect that I'm calling set_data on the wrong object, but I can't find any documentation on what the right object is. Can you help? Thanks.
Here's the full code:
import numpy as np
import matplotlib as mpl
import matplotlib.mlab as mlab
import matplotlib.pyplot as pyl
from matplotlib.contour import QuadContourSet
from matplotlib.widgets import Slider
#Define display parameters
mpl.rcParams['xtick.direction'] = 'out'
mpl.rcParams['ytick.direction'] = 'out'
delta = 0.025
#Define model parameters
alpha = .5
beta = .5
x_bar, a, b, c = 2, 0, 1, .1
v = np.arange(0, 10, delta)
w = np.arange(0, 10, delta)
#Calculate grid values
V, W = np.meshgrid(v,w)
Z = (V**(beta))*(W**(1-beta))
X = x_bar + a + b*Z
U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V)
# Plot
fig = pyl.figure()
ax = fig.add_subplot(221)
CS = QuadContourSet(pyl.gca(), V, W, U, 200)
pyl.clabel(CS, inline=1, fontsize=10)
pyl.title('Simplest default with labels')
#Define slider for alpha
axcolor = 'lightgoldenrodyellow'
alpha_axis = pyl.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
alpha_slider = Slider(alpha_axis, 'Amp', 0, 1, valinit=.5)
def update(val):
alpha = alpha_slider.val
U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V)
CS.set_data(V, W, U)
pyl.draw()
alpha_slider.on_changed(update)
pyl.show()

The problem is that the QuadContourSet object has no way to update its data, since if you change the data arbitrarily, the whole thing needs to be recomputed. I don't know if there is something about your particular way of generating data that would lend itself to a simpler way to modify the contour lines, but if not, I think what you need to do is to plot the contours from scratch:
# After your "Define model parameters" block
def compute_and_plot(ax, alpha):
#Calculate grid values
V, W = np.meshgrid(v,w)
Z = (V**(beta))*(W**(1-beta))
X = x_bar + a + b*Z
U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V)
CS = QuadContourSet(ax, V, W, U, 200)
pyl.clabel(CS, inline=1, fontsize=10)
# Plot
fig = pyl.figure()
pyl.title('Simplest default with labels')
ax = fig.add_subplot(221)
compute_and_plot(ax, alpha)
#Define slider for alpha
axcolor = 'lightgoldenrodyellow'
alpha_axis = pyl.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
alpha_slider = Slider(alpha_axis, 'Amp', 0, 1, valinit=.5)
def update(ax, val):
alpha = alpha_slider.val
ax.cla()
compute_and_plot(ax, alpha)
pyl.draw()
alpha_slider.on_changed(lambda val: update(ax, val))
pyl.show()

Related

Put a slider right under a subplot in matplotlib

I'm trying to put a slider right under the x-axis of a subplot in matplotlib, so that both start and end at the same value. Is there an easy way to do that, meaning that I don't have to find the right coordinates and put them myself when I create the plt.axe containing the slider?
You could use ax.get_position() to get x0, y0, width and height of the axis and use this to define the positions for the axes of the slider.
I adapted the matplotlib example to show a use case:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.3)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
delta_f = 5.0
s = a0 * np.sin(2 * np.pi * f0 * t)
l, = plt.plot(t, s, lw=2)
ax.margins(x=0)
axcolor = 'lightgoldenrodyellow'
def xaligned_axes(ax, y_distance, width, **kwargs):
return plt.axes([ax.get_position().x0,
ax.get_position().y0-y_distance,
ax.get_position().width, width],
**kwargs)
axfreq = xaligned_axes(ax=ax, y_distance=0.1, width=0.03, facecolor=axcolor)
axamp = xaligned_axes(ax=ax, y_distance=0.15, width=0.03, facecolor=axcolor)
sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0, valstep=delta_f)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
def update(val):
amp = samp.val
freq = sfreq.val
l.set_ydata(amp*np.sin(2*np.pi*freq*t))
fig.canvas.draw_idle()
sfreq.on_changed(update)
samp.on_changed(update)
But as you have to use plt.subplots_adjust(bottom=0.3) to have enough space below the plot and you need to define the width and the distance to the axis in y direction I guess you do not win that much.

How to make two sliders in matplotlib

I would like to make two sliders in matplotlib to manually change N and P values in my predator-prey model:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def lotka(x,t,params):
N, P = x
alpha, beta, gamma, delta = params
derivs = [alpha*N - beta*N*P, gamma*N*P - delta*P]
return derivs
N=2
P=1
alpha=3
beta=0.5
gamma=0.4
delta=3
params = [alpha, beta, gamma, delta]
x0=[N,P]
maxt = 20
tstep = 0.01
t=np.arange(0,maxt,tstep)
equation=odeint(lotka, x0, t, args=(params,))
plt.plot(t,equation)
plt.xlabel("Time")
plt.ylabel("Population size")
plt.legend(["Prey", "Predator"], loc="upper right")
plt.title('Prey & Predator Static Model')
plt.grid(color="b", alpha=0.5, linestyle="dashed", linewidth=0.5)
This is my code which produces a graph for fixed initial values of N and P. However, I'd like to change them to see how the plot changes. And for this, I'd like to use sliders like: http://matplotlib.org/users/screenshots.html#slider-demo but I do not know how to add this into my code...
Could anyone please give me any direction? Many thanks!! xx
From the example, hope the comments help you understand what's what:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
from scipy.integrate import odeint
# Function to draw
def lotka(x, t, params):
N, P = x
alpha, beta, gamma, delta = params
derivs = [alpha*N - beta*N*P, gamma*N*P - delta*P]
return derivs
# Parameters
Nmin = 1
Nmax = 100
Pmin = 1
Pmax = 100
N0 = 2
P0 = 1
alpha = 3
beta = 0.5
gamma = 0.4
delta = 3
params = [alpha, beta, gamma, delta]
x0=[N0,P0]
maxt = 20
tstep = 0.01
# Initial function values
t = np.arange(0, maxt, tstep)
prey, predator = odeint(lotka, x0, t, args=(params,)).T
# odeint returne a shape (2000, 2) array, with the value for
# each population in [[n_preys, n_predators], ...]
# The .T at the end transponses the array, so now we get each population
# over time in each line of the resultint (2, 2000) array.
# Create a figure and an axis to plot in:
fig = plt.figure()
ax = fig.add_axes([0.10, 0.3, 0.8, 0.6])
prey_plot = ax.plot(t, prey, label="Prey")[0]
predator_plot = ax.plot(t, predator, label="Predator")[0]
ax.set_xlabel("Time")
ax.set_ylabel("Population size")
ax.legend(loc="upper right")
ax.set_title('Prey & Predator Static Model')
ax.grid(color="b", alpha=0.5, linestyle="dashed", linewidth=0.5)
ax.set_ylim([0, np.max([prey, predator])])
# create a space in the figure to place the two sliders:
axcolor = 'lightgoldenrodyellow'
axis_N = fig.add_axes([0.10, 0.1, 0.8, 0.03], facecolor=axcolor)
axis_P = fig.add_axes([0.10, 0.15, 0.8, 0.03], facecolor=axcolor)
# the first argument is the rectangle, with values in percentage of the figure
# size: [left, bottom, width, height]
# create each slider on its corresponding place:
slider_N = Slider(axis_N, 'N', Nmin, Nmax, valinit=N0)
slider_P = Slider(axis_P, 'P', Pmin, Pmax, valinit=P0)
def update(val):
# retrieve the values from the sliders
x = [slider_N.val, slider_P.val]
# recalculate the function values
prey, predator = odeint(lotka, x, t, args=(params,)).T
# update the value on the graph
prey_plot.set_ydata(prey)
predator_plot.set_ydata(predator)
# redraw the graph
fig.canvas.draw_idle()
ax.set_ylim([0, np.max([prey, predator])])
# set both sliders to call update when their value is changed:
slider_N.on_changed(update)
slider_P.on_changed(update)
# create the reset button axis (where its drawn)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
# and the button itself
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
slider_N.reset()
slider_P.reset()
button.on_clicked(reset)
Notice, however, you should have shown how you tried to adapt the example to what you had and how it was misbehaving.
Nevertheless, welcome to Stackoverflow.
So, I have tried with this code:
from scipy import integrate
from matplotlib.widgets import Slider, Button, RadioButtons
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
plt.xlabel("Time")
plt.ylabel("Population size")
plt.legend(["Prey", "Predator"], loc="upper right")
plt.title('Prey & Predator Static Model')
plt.grid(color="b", alpha=0.5, linestyle="dashed", linewidth=0.5)
l1, l2 = plt.plot(t, equation)
axcolor = 'b'
ax_N = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
ax_P = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
sN = Slider(ax_N, 'N', 0, 80, valinit=1)
sP = Slider(ax_P, 'P', 0, 80, valinit=1)
def update(val):
N = N*sN.val
P = P*sP.val
x = equation
fig.canvas.draw_idle()
l1, l2.set_ydata(y)
ax.set_ylim(y.min(), y.max())
draw()
sN.on_changed(update)
sP.on_changed(update)
plt.show()
I could not manipulate the sliders. Thank you so much #berna1111

Quiver plot with slider in Bokeh

I have developed a code that works perfectly fine but now I want to show it to my professor without always having to take my computer with me. The code is:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
a = 0.5
X, Y = np.mgrid[0:1.05:0.025, 0:1.05:0.025]
varX = #Some equation with X, Y and a (as a parameter)
varY = #Some other equation
U = varX-X
V = varY-Y
length = np.sqrt(U**2 + V**2)
fig, ax = plt.subplots()
Q = plt.quiver(X, Y, varX-X, varY-Y,
color='r',
scale=3*(2 ** .5), units='y')
plt.subplots_adjust(left=0.25, bottom=0.25)
plt.axis([0, 1, 0, 1])
axcolor = 'lightgoldenrodyellow'
axa = plt.axes([0.25, 0.10, 0.65, 0.03], axisbg=axcolor)
sa = Slider(axa, 'Alfa', 0, 1, valinit=a)
def update(val):
a = sa.val
varX = #Same equation as before
varY = #Same equation
Q.set_UVC(varX - X, varY - Y)
fig.canvas.draw_idle()
sa.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
def reset(event):
sa.reset()
button.on_clicked(reset)
plt.show()
As I said, this code works like a charm, but how could I "save" the result? I have thought on making an html-js version, but couldn't make a Bokeh similar version for it and mpld3 doesn't seem to support sliders...
Thanks in advance,
Javirk
finally I could figure it out myself. I had to use "segment" instead of "multi_line" because I didn't want to set up a server. The code:
from __future__ import division
import numpy as np
from bokeh.layouts import row, widgetbox
from bokeh.models import CustomJS, Slider
from bokeh.plotting import figure, output_file, show, ColumnDataSource
#Declaration of variables
xx = np.linspace(0, 1, 50)
yy = np.linspace(0, 1, 50)
Y, X = np.meshgrid(xx, yy)
x0 = X[::2, ::2].flatten()
y0 = Y[::2, ::2].flatten()
#Equations and so, result: x1,y1 with same dimensions as x0,y0
#x1,y1 are the coordinates of the final point of the segment
source = ColumnDataSource(data=dict(x0=x0, y0=y0, x1=x1, y1=y1))
#Plot
plot = figure(x_range=(0, 1), y_range=(0, 1), x_axis_label='H', y_axis_label='C',
title="Retrato de fases. Modelo simplificado")
plot.segment('x0', 'y0', 'x1', 'y1', source=source, line_width=1)
#JS function that activates when slider value is changed
callback = CustomJS(args=dict(source=source), code="""
var data = source.data;
var alpha = alpha.value;
x0 = data['x0'];
y0 = data['y0'];
x1 = data['x1'];
y1 = data['y1'];
for (i = 0; i < x0.length; i++) {
#Same equations as before, but written in JS
}
source.trigger('change');
""")
#Set up all the sliders
alfa_slider = Slider(start=0, end=1, value=alpha, step=.01, title="Alpha", callback=callback)
callback.args["alpha"] = alpha_slider
output_file("slider.html", title="Phase Portrait")
layout = row(
plot,
widgetbox(alpha_slider),
)
show(layout)

Python matplotlib: position colorbar in data coordinates

I would like to position a colorbar inside a scatter plot by specifying the position in data coordinates.
Here is an example of how it works when specifying figure coordinates:
import numpy as np
import matplotlib.pyplot as plt
#Generate some random data:
a = -2
b = 2
x = (b - a) * np.random.random(50) + a
y = (b - a) * np.random.random(50) + a
z = (b) * np.random.random(50)
#Do a scatter plot
fig = plt.figure()
hdl = plt.scatter(x,y,s=20,c=z,marker='o',vmin=0,vmax=2)
ax = plt.gca()
ax.set_xlim([-2,2])
ax.set_ylim([-2,2])
#Specifying figure coordinates works fine:
fig_coord = [0.2,0.8,0.25,0.05]
cbar_ax = fig.add_axes(fig_coord)
clevs = [0, 1 , 2]
cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)
plt.show()
...Ok, can't include an image of the plot here because I am lacking reputation. But the above code will give you an impression....
Now the question is, how could I position the colorbar at data coordinates, to appear at e.g.:
left, bottom, width, height: -1.5, 1.5, 1, 0.25
I have experimented with a few things, like determining the axes position within the figure and transforming it to data coordinates but didn't succeed.
Many thanks for ideas or pointing me to already answered similar questions!
Here is what I did (not particularly beautiful but it helps). Thanks tcaswell !
#[lower left x, lower left y, upper right x, upper right y] of the desired colorbar:
dat_coord = [-1.5,1.5,-0.5,1.75]
#transform the two points from data coordinates to display coordinates:
tr1 = ax.transData.transform([(dat_coord[0],dat_coord[1]),(dat_coord[2],dat_coord[3])])
#create an inverse transversion from display to figure coordinates:
inv = fig.transFigure.inverted()
tr2 = inv.transform(tr1)
#left, bottom, width, height are obtained like this:
datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0],tr2[1,1]-tr2[0,1]]
#and finally the new colorabar axes at the right position!
cbar_ax = fig.add_axes(datco)
#the rest stays the same:
clevs = [0, 1 , 2]
cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)
plt.show()
Here is what I did, based on the comments to my original question:
import numpy as np
import matplotlib.pyplot as plt
a = -2
b = 2
x = (b - a) * np.random.random(50) + a
y = (b - a) * np.random.random(50) + a
z = (b) * np.random.random(50)
fig = plt.figure()
hdl = plt.scatter(x,y,s=20,c=z,marker='o',vmin=0,vmax=2)
ax = plt.gca()
ax.set_xlim([-2,2])
ax.set_ylim([-2,2])
#[(lower left x, lower left y), (upper right x, upper right y)] of the desired colorbar:
dat_coord = [(-1.5,1.5),(-0.5,1.75)]
#transform the two points from data coordinates to display coordinates:
tr1 = ax.transData.transform(dat_coord)
#create an inverse transversion from display to figure coordinates:
inv = fig.transFigure.inverted()
tr2 = inv.transform(tr1)
#left, bottom, width, height are obtained like this:
datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0],tr2[1,1]-tr2[0,1]]
#and finally the new colorabar axes at the right position!
cbar_ax = fig.add_axes(datco)
#the rest stays the same:
clevs = [0, 1 , 2]
cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)
plt.show()
Two step to specify the position in data coordinates of an Axes:
use Axes.set_axes_locator() to set a function that return a Bbox object in figure coordinate.
set the clip box of all children in the Axes by set_clip_box() method:
Here is the full code:
import numpy as np
import matplotlib.pyplot as plt
#Generate some random data:
a = -2
b = 2
x = (b - a) * np.random.random(50) + a
y = (b - a) * np.random.random(50) + a
z = (b) * np.random.random(50)
#Do a scatter plot
fig = plt.figure()
hdl = plt.scatter(x,y,s=20,c=z,marker='o',vmin=0,vmax=2)
ax = plt.gca()
ax.set_xlim([-2,2])
ax.set_ylim([-2,2])
#Specifying figure coordinates works fine:
fig_coord = [0.2,0.8,0.25,0.05]
cbar_ax = fig.add_axes(fig_coord)
def get_ax_loc(cbar_ax, render):
from matplotlib.transforms import Bbox
tr = ax.transData + fig.transFigure.inverted()
bbox = Bbox(tr.transform([[1, -0.5], [1.8, 0]]))
return bbox
clevs = [0, 1 , 2]
cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)
def get_ax_loc(cbar_ax, render):
from matplotlib.transforms import Bbox
tr = ax.transData + fig.transFigure.inverted()
bbox = Bbox(tr.transform([[1, -0.5], [1.8, 0]]))
return bbox
def set_children_clip_box(artist, box):
for c in artist.get_children():
c.set_clip_box(box)
set_children_clip_box(c, box)
cbar_ax.set_axes_locator(get_ax_loc)
set_children_clip_box(cbar_ax, hdl.get_clip_box())
plt.show()
And here is the output:

How to make four-way logarithmic plot in Matplotlib?

Four-way logarithmic plot is a very often used graph for vibration control and earthquake protection. I am quite interesting in how this plot can be plotted in Matplotlib instead of adding axes in Inkscape. A sample of Four-way logarithmic plot is here.
A quick and dirty Python code can generate main part of the figure, but I cannot add the two axes onto the figure. http://matplotlib.org/examples/axes_grid/demo_curvelinear_grid.html provides an example of adding axes, but I fails to make it working. Anyone has similar experience on adding axes to Matplotlib figure?
from pylab import *
from mpl_toolkits.axisartist.grid_helper_curvelinear import GridHelperCurveLinear
from mpl_toolkits.axisartist import Subplot
beta=logspace(-1,1,500)
Rd={}
for zeta in [0.01,0.1,0.2,0.7,1]:
Rd[zeta]=beta/sqrt((1-beta*beta)**2+(2*beta*zeta)**2)
loglog(beta,Rd[zeta])
ylim([0.1,10])
xlim([0.1,10])
grid('on',which='minor')
Update: Thank you all! I use Inkscape to modify the figure above. I think the result is just fine. However, I am still looking for methods to draw this figure in Matplotlib.
Here is a partial solution. I am still working on how to do all of this in a natural loglog() plot rather than scaling the data. (To complete this example you would have to define custom tick-lables so that they display 10**x rather than x.)
%matplotlib inline # I am doing this in an IPython notebook.
from matplotlib import pyplot as plt
import numpy as np
from numpy import log10
# Generate the data
beta = np.logspace(-1, 1, 500)[:, None]
zeta = np.array([0.01,0.1,0.2,0.7,1])[None, :]
Rd = beta/np.sqrt((1 - beta*beta)**2 + (2*beta*zeta)**2)
def draw(beta=beta, Rd=Rd):
plt.plot(log10(beta), log10(Rd))
plt.ylim([log10(0.1), log10(10)])
plt.xlim([log10(0.1), log10(10)])
plt.grid('on',which='minor')
ax = plt.gca()
ax.set_aspect(1)
from mpl_toolkits.axisartist import GridHelperCurveLinear
from matplotlib.transforms import Affine2D
from mpl_toolkits.axisartist import SubplotHost
from mpl_toolkits.axisartist import Subplot
#tr = Affine2D().rotate(-np.pi/2)
#inv_tr = Affine2D().rotate(np.pi/2)
class Transform(object):
"""Provides transforms to go to and from rotated grid.
Parameters
----------
ilim : (xmin, xmax, ymin, ymax)
The limits of the displayed axes (in physical units)
olim : (xmin, xmax, ymin, ymax)
The limits of the rotated axes (in physical units)
"""
def __init__(self, ilim, olim):
# Convert each to a 3x3 matrix and compute the transform
# [x1, y1, 1] = A*[x0, y0, 1]
x0, x1, y0, y1 = np.log10(ilim)
I = np.array([[x0, x0, x1],
[y0, y1, y1],
[ 1, 1, 1]])
x0, x1, y0, y1 = np.log10(olim)
x_mid = (x0 + x1)/2
y_mid = (y0 + y1)/2
O = np.array([[ x0, x_mid, x1],
[y_mid, y1, y_mid],
[ 1, 1, 1]])
self.A = np.dot(O, np.linalg.inv(I))
self.Ainv = np.linalg.inv(self.A)
def tr(self, x, y):
"""From "curved" (rotated) coords to rectlinear coords"""
x, y = map(np.asarray, (x, y))
return np.dot(self.A, np.asarray([x, y, 1]))[:2]
def inv_tr(self, x, y):
"""From rectlinear coords to "curved" (rotated) coords"""
x, y = map(np.asarray, (x, y))
return np.dot(self.Ainv, np.asarray([x, y, 1]))[:2]
ilim = (0.1, 10)
olim = (0.01, 100)
tr = Transform(ilim + ilim, olim + olim)
grid_helper = GridHelperCurveLinear((tr.tr, tr.inv_tr))
fig = plt.gcf()
ax0 = Subplot(fig, 1, 1, 1)
ax1 = Subplot(fig, 1, 1, 1, grid_helper=grid_helper, frameon=False)
ax1.set_xlim(*np.log10(olim))
ax1.set_ylim(*np.log10(olim))
ax1.axis["left"] = ax1.new_floating_axis(0, 0.)
ax1.axis["bottom"] = ax1.new_floating_axis(1, 0.0)
fig.add_subplot(ax0)
fig.add_subplot(ax1)
ax0.grid('on', which='both')
ax1.grid('on', which='both')
plt.plot(log10(beta), log10(Rd))
plt.ylim(np.log10(ilim))
plt.xlim(np.log10(ilim))
This seems to be a bit tricker than it should. There are ways to center the spines (axis lines), and ways to rotate them, but those do not work together. Adding a normal axis on a line (a la mpl demos) results in a curved axis (because it is logarithmic). Here is a [poor] example of how to draw -- as in, like you would with Inkscape something to look like an additional pair of axis spines with the example data.
import matplotlib.pyplot as plt
import numpy as np
#data
b = np.logspace(-1, 1, 500)
Rd = {}
for zeta in [0.01, 0.1, 0.2, 0.7, 1]:
Rd[zeta] = b / np.sqrt((1 - b * b) ** 2 + (2 * b * zeta) ** 2)
#plot
fig = plt.figure()
ax1 = fig.add_subplot(111)
for z in Rd:
ax1.loglog(b, Rd[z])
ax1.set_xlim([0.1, 10])
ax1.set_ylim([0.1, 10])
ax1.set_aspect(1.)
#draw lines to look like diagonal spines (axes)
xmin, xmax = ax1.get_xlim() # xlim == ylim
a = np.log10(xmin)
b = np.log10(xmax)
span = b - a
period_points = 3 # number of points/ticks per decade
npts = (span * period_points) + 1 # +1 for even powers of 10
x1 = np.logspace(a, b, num=npts)
x2 = np.logspace(b, a, num=npts)
ax1.plot(x1, x1, color='k', marker='x', ms='9')
ax1.plot(x1, x2, color='k', marker='x', ms='9')
#NOTE: v1.2.1 lacks 'TICKUP' and similar - these may be
# a better choice in v1.3x and beyond
ax1.text(0.97, 0.9,
"axis label: A",
size='large',
horizontalalignment='right',
verticalalignment='top',
rotation=45,
transform=ax1.transAxes,
#bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10},
)
ax1.text(0.03, 0.9,
"axis label: B",
size='large',
horizontalalignment='left',
verticalalignment='top',
rotation=-45,
transform=ax1.transAxes,
#bbox={'facecolor': 'white', 'alpha': 0.5, 'pad': 10},
)
plt.savefig("example.pdf")

Categories