• Welcome to my blog which mainly focuses on topics of interest to me as a postdoctoral researcher and cosmologist. More Info and my CV

Minor Tick Labels in Matplotlib

This is a slightly more technical post than usual but having figured out how to do something quite esoteric in Matplotlib I thought I would write it down to save me remembering.

I have been making quite a few plots recently for a paper which should hit the arXiv very soon. The Python plotting package Matplotlib has been indispensable in this regard, especially as I took the effort of creating a script which creates all the plots. This meant that redoing all the graphs for new results or with changed sizes etc. was a simple as rerunning the script.

Quite a few of the plots use log axes and while Matplotlib performs admirably there was one problem I had with certain plots. By default, the log plots only show tick labels for each order of magnitude. Tick labels are the numbers on the x or y axis telling you the corresponding numerical value, and when the figure is zoomed in it is possible to lose the major tick label at say 10-4 because you only want to plot values from 0.3×10-4 and 0.5×10-4. Obviously this removes all sense of scale from the plot. A very mediocre solution is to just zoom out until a major tick label is back in the plot but this is obviously unsatisfactory.

I looked through the Matplotlib documentation, which has very detailed information about the API and has a lot of examples, but unfortunately didn’t address this exact point. After a bit of searching I found a useful conversation on the users mailing list which got me close but didn’t use the LaTeX labels which are really essential for publication quality graphs (in my opinion anyway!). The tick labels documentation along with the major-minor ticks example led me to the Formatter classes, especially LogFormatter and LogFormatterMathtext. This looked like the right answer but unfortunately LogFormatterMathtext writes the minor tick labels in a very unusual way. Instead of 0.3×10-4 it only writes an exponent, so 10-4.52.

I finally settled on extending the pyplot.LogFormatter class which controls the text for the tick labels. My subclass is as follows:

import re
import pylab

class LogFormatterTeXExponent(pylab.LogFormatter, object):
    """Extends pylab.LogFormatter to use
    tex notation for tick labels."""

    def __init__(self, *args, **kwargs):
        super(LogFormatterTeXExponent,
              self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        """Wrap call to parent class with
        change to tex notation."""
        label = super(LogFormatterTeXExponent,
                      self).__call__(*args, **kwargs)
        label = re.sub(r'e(\S)0?(\d+)',
                       r'\\times 10^{\1\2}',
                       str(label))
        label = "$" + label + "$"
        return label

It is provided as is, but there shouldn’t be too much wrong with it. One odd thing is that the LogFormatter class is an old style class, so I inherited from object to make it my subclass a new style class. This might be dangerous and cause some unexpected problems.

To use the class you can do something like the following:

import pylab
import numpy as np

fig = pylab.figure()
pylab.semilogy(np.logspace(-6,-5))
ax = fig.gca()
ax.yaxis.set_minor_formatter(
    LogFormatterTeXExponent(base=10,
     labelOnlyBase=False))
pylab.draw()

Below are three different figures showing the current default situation, the result of using LogFormatterMathtext and the result of the new class. I hope this will be of use to someone who has been struggling with this problem as I have.

As I mentioned, this came up because of a paper that is very nearly completed and should be available soon. Along with the paper we should have the long promised release of the code I have been working on which solves cosmological perturbation equations during inflation. More on that soon.

Posted in Tools | Tagged , , , , , | Leave a comment

Adam Christopherson awarded prestigious RAS fellowship!

Many congratulations to Adam Christopherson who has been awarded the prestigious Sir Norman Lockyer Fellowship of the Royal Astronomical Society. The three year fellowship is awarded “to enable an outstanding research worker to conduct a self-directed programme of research in any astronomical topic”.

Adam joined Queen Mary as a PhD student a year after I did and it’s been great sharing an office with him over the past few years. Although we haven’t yet written a paper together we’ve thrown a lot of ideas around so hopefully we can work together on something soon. When it comes to listing the names I imagine he will be arguing for alphabetical order!

Adam will be taking up his fellowship in the University of Nottingham from October 2011.

Posted in QMUL | Tagged , , , , | Leave a comment

Science Cuts: One Day Left

The results of the Comprehensive Spending Review are being announced tomorrow and the feeling in the astrophysics community is increasingly pessimistic about the size of the cuts to research funding. With one day to go until the broad outline of the cuts is given, rumours are running wild that STFC will have to cut major programmes, exit from international collaborations and in the worst case scenario start to claw back grants which have already been awarded.

Peter Coles has a post summarizing the current swarm of rumours, and Andy Lawrence has a poll where you can pick your poison cuts-wise. At this late stage the mainstream media has finally started picking up on the message of the Science Is Vital campaign, that cuts in research funding are a ruinous road to lower growth in the future. The Guardian and The Times have both had editorials denouncing cuts to science funding in the last few days, while the FT got in ahead of the curve. Jon Snow has been outlining the possible brain drain, and the BBC have given a platform to CASE‘s Imran Khan. But is it too late to change the headline figures? The claim is that most if not all the deals are done at least as far as headline figures go. The Department of Business Innovation and Skills, which is responsible for research funding, is rumoured to be the one holdout left. Whether this indicates a change in attitude in Whitehall or an entrenched position in the Treasury, we will find out tomorrow.

A word of warning though, the announcements tomorrow are probably going to be broad and impenetrable. Colin Talbot has produced a handy guide to what to expect. (Charlie Brooker provides some light relief in his advice to George Osbourne.) The resultant changes in the budgets of the research councils, and particularly STFC, may not be known until December, when the axe will truly start to fall.

Update: 20:00 19/10 According to this Guardian story, the science research budget may escape the deepest cuts, and retain “flat cash”, in other words an approximately 10% decrease in four years, depending on inflation.

Posted in Campaign, Research | Tagged , , , , , , , , | Leave a comment

Inspire Beta: New Interface to SPIRES database

INSPIRE BetaA colleague mentioned today that the front page of the venerable SPIRES database of High Energy Physics papers is now promoting the new Inspire interface which was announced a few years ago.

The website for the current beta phase of the project is http://inspirebeta.net.

It is unclear to me whether “Beta” is part of the site name, as suggested by the URL and the text on the INSPIRE page, or whether this is just the beta phase of the INSPIRE project as the SPIRES homepage seems to imply. It would certainly be an odd decision to use a different URL for the beta phase and force everyone to change bookmarks, references in blogs, literature etc., once the beta phase is over.

These are quick first impressions because I haven’t had much time to use the new service. First off it is fast. Very fast. So fast that when searching for my name INSPIRE claims that the “Search took 0.00 seconds”. It feels almost instantaneous. This might be because of a light load before the hordes using SPIRES are switched over. It is certainly an improvement on the interminable and often futile stretches of time needed with the SPIRES engine.

Read More »

Posted in arXiv, Research, Tools | Tagged , , , , , , , , | Leave a comment

Scientists on the march*

Adam and Gráinne get the message out

Adam and Gráinne get the message out

On Saturday many bemused tourists wandering around Westminster were treated to the unusual sight of scientists roaming free from their offices and labs to gather in protest at the government’s planned cuts to research funding.

The rally was organised by Science is Vital who are also organising a petition and lobby of MPs which I talked about last week. There was a great turnout at the rally with some very inventive banners and placards. There are lots of pictures and videos on the web including some heart-felt but perhaps ill-advised singing embedded below.

No more Dr (and Mr) nice guys

No more Dr (and Mr) nice guys!

The rally was a great success but the work has only just begun. The petition is still open and the lobby in the Houses of Parliament will take place tomorrow Tuesday 12th.

Once the broad outline of the cuts is known on the 20th of October I would expect a further bout of activity depending on the severity of the results. Just today the possibility of a second wave of cuts on top of the original amount has come to light.

Well done to all the organisers of the rally and thank you to all the speakers for making the case so forcefully!


Video of singing at the rally by alewc0283

* Well more of a rally really.

Posted in Campaign, Research | Tagged , , , , , , , | Leave a comment
Bear