|
From: KURT P. <pet...@ms...> - 2013-10-01 23:36:42
|
> Subject: Re: [Matplotlib-users] x axis non-uniform labeling (KURT PETERS)
> From: sm...@fu...
> Date: Tue, 1 Oct 2013 11:34:39 -0700
> CC: pmh...@gm...; mat...@li...
> To: pet...@ms...
>
>
> On Oct 1, 2013, at 8:59AM, KURT PETERS wrote:
>
> >
> > REPLY:
> > ============================================================
> >
> > here's what SHOULD be happening
> >
> > | 0 1 5 9 13 18 21 24 25 28
> > 3 | x
> > | x x
> > | x x
> > | x x
> > -1|_x__________________x_____
> > 1 2 3 4 5 6 7 8 9 10
> >
> > How can I make that happen? Instead, MPL is autoranging the top axis. I don't want that I just want the actual labels to occur up there.
> >
> > Kurt
>
> Kurt,
>
> Here is a self-contained example of what I think you are asking for:
>
> {{{
> import matplotlib.pyplot as plt
> import numpy as np
> from matplotlib.ticker import FuncFormatter, MaxNLocator
>
> simtimedata = np.array([0, 1, 5, 9, 13, 18, 21, 24, 25, 28, 31, 32, 41, 55, 56, 57])
> idatanp = np.array([-1,0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0, -1, -2])
> xdat = range(len(simtimedata))
> fig = plt.figure()
>
> ax1 = fig.add_subplot(211)
> ax1.plot(xdat,idatanp)
> ax1.grid(True)
> ax2 = fig.add_subplot(212)
> ax2.plot(xdat, idatanp.real,'k-o')
> def index_to_label(i,dummy):
> if i >= 0 and i < len(simtimedata):
> return str(simtimedata[i])
> else:
> return ''
>
> form = FuncFormatter(index_to_label)
> ax2.xaxis.set_major_formatter(form)
>
> #ax2.set_title("time domain")
> ax2.grid(True)
> plt.show()
> }}}
>
> You may also be interested in this question and answer on stackoverflow:
> http://stackoverflow.com/questions/3918028/how-do-i-plot-multiple-x-or-y-axes-in-matplotlib
>
> -Sterling
>
Thanks Sterling,
That's exactly what I was looking for. I ended up creating a class because I wasn't comfortable using either a lambda function or simtimedata as a global variable (just a style issue). In case someone's been following along and wants the final code:
...
from matplotlib.ticker import Formatter
class MyFormatter(Formatter):
def __init__(self, simtime):
self.simtime = simtime
def __call__(self,val,pos=0):
if val >= 0 and val < len(self.simtime):
return str(self.simtime[val])
else:
return ''
xdat=np.arange(0,10)
simtimedata = np.array([ 0, 1, 5, 9, 13, 18, 21, 24, 25, 28])
idatanp = np.array ([-1,0, 1, 2, 3, 2, 1, 0, -1, -2])
print idatanp.shape
print simtimedata.shape
print xdat.shape
fig = plt.figure()
intformatter = MyFormatter(simtimedata)
ax1 = fig.add_subplot(211)
ax1.plot(xdat,idatanp)
ax1.grid(True)
ax2 = fig.add_subplot(212)
ax2.plot(xdat, idatanp.real,'k-o')
ax2.xaxis.set_major_formatter(intformatter)
ax2.set_title("time domain")
ax2.grid(True)
plt.show()
|