6

I am trying to plot a figure with two x-axis, which are non-linear to each other, with matplotlib. The plot I want to get is like this:

Plot

Basically, the age is dependent on red shift. It's non linear and need to be calculated. I want to make both age and red shift as x-axis. How can I make it?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Fxyang
  • 293
  • 3
  • 6
  • 12

2 Answers2

4

The function twiny() may be what you're looking for.

import matplotlib.pyplot as plt
plt.loglog(range(100))
ax1 = plt.gca()
ax2 = ax1.twiny()
ax2.set_xticks([100,80,50])
ax2.set_xticklabels(['0','1','2'])
ax1.set_xlabel('redshift')
ax2.set_xlabel('age')
plt.show()

example plot for twiny() function

Max Leske
  • 5,007
  • 6
  • 42
  • 54
Kyler Brown
  • 1,106
  • 7
  • 18
  • I did, but was unable to post the plot as I lack the reputation. – Kyler Brown Feb 13 '13 at 05:11
  • I didn't get the point of this function. It seems that the two x-axis are still linear to each other. – Fxyang Feb 13 '13 at 05:12
  • 1
    I guess I assumed by non-linear you meant logarithmic. xticks will place arbitrary ticks, xticklabels can label them. Hope that helps. – Kyler Brown Feb 13 '13 at 05:15
  • By non-linear, I mean the age can be calculated from redshift through an integral, which is more complicated than logarithmic. – Fxyang Feb 13 '13 at 18:58
0

I did this like this:

from mpl_toolkits.axes_grid.parasite_axes import SubplotHost 
fig = plt.figure(1, figsize=(figwidth,figheight))
ax = SubplotHost(fig, 1,1,1) 
fig.add_subplot(ax)

#plotting as usual

ax2 = ax.twin() # ax2 is responsible for "top" axis and "right" axis
ax2.axis["right"].toggle(ticklabels=False)
ax2.xaxis.set_major_formatter(FuncFormatter(fmt_zToEta)) #set eta coord format

#with a function for the Z to eta transform for plot labels
def fmt_zToEta(x, pos=None):
    #...
    return transformed_label 

I also remember starting off with that redshift example ;-)

I think the SubPlotHost thing is necessary, but I'm not 100% sure, since I ripped this out of an existing (sub)plot of mine without checking if it runs nicely without.

Edit: also, see https://stackoverflow.com/a/10517481/599884

Community
  • 1
  • 1
Christoph
  • 5,480
  • 6
  • 36
  • 61