# Plotting an additional axis with ticks

When preparing non-standard graphs, it is common that one needs an "extra" axis, parallel but displaced from a traditional axis. This might happen in many cases:

A generic solution is to create a plot with the relevant axis, keep only the axis (by making the data transparent or something), and use Overlay. However, this produces an object which is not a Graphics, and thus is not amenable to further manipulations.

Thus, it would be very useful to have a function that generates a second axis with ticks and labels. Alternatively, it would be nice to have a clever way to position an axis in a plot in an exact way (i.e. a way that respects the data) without using Overlay.

• Sep 15, 2015 at 21:17
• If you don't mind two axes at different sides of the graph (reference.wolfram.com/language/howto/…). Sep 15, 2015 at 21:56
• @AlexeyPopkov Thanks. But that only works if you have only two curves (I've linked to a similar solution in one of the references) Sep 16, 2015 at 5:28
• @yohbs The solution by LLlAMnYP can be used for adding arbitrary number of Insets with coordinate systems exactly aligned to the coordinate system of the parent plot. Each Inset may contain only axis or both axis and curve. It requires quite a bit of careful work to develop a generic solution though. Sep 16, 2015 at 5:50

Here I am adapting LLlAMnYP's answer, and I hope that it can meet the requirements. If someone can tell me how to better handle the options statement than by the kludgy Which statement I would be most appreciative.

Options[extraAxisPlot] = {"AxisType" -> "xAxis",
"AxisOptions" -> {}, "ExtraEpilog" -> {}};
extraAxisPlot[plot_, {axisStart_, axisFinish_}, {xpos_, ypos_},
OptionsPattern[]] := Module[
{printerPointsPlotRange, realImageDimensions, realPlotRange,
plotRangeRatio,
axisplotrange, axisxrange, axisaxes, insetpos, axis},
printerPointsPlotRange = (#[] - #[] &)@(Rasterize[
Show[#, Epilog -> {Annotation[
Rectangle[Scaled[{0, 0}], Scaled[{1, 1}]],
"Two",
"Region"]}], "Regions"][[-1, 2]]) &;
realImageDimensions = (#[] - #[] &)@(Rasterize[
Show[#, Epilog -> {Annotation[

Rectangle[ImageScaled[{0, 0}], ImageScaled[{1, 1}]],
"Two", "Region"]}], "Regions"][[-1, 2]]) &;
realPlotRange =

Total /@ (Options[#, PlotRangePadding][[-1, 2]] /.
None -> 0),
baserange = (#[] - #[] &) /@ PlotRange[#], range},

range = (baserange + padding) /. {a_ Scaled[b_] -> Scaled[a b],
Scaled[a_] + Scaled[b_] -> Scaled[a + b]} /. {a_ +
Scaled[b_] -> a/(1 - b)};
range] &;
plotRangeRatio = realPlotRange[#1]/realPlotRange[#2] &;
{axisplotrange, axisxrange, axisaxes, insetpos} =
Which[OptionValue["AxisType"] == "xAxis",
{{{axisStart, axisFinish}, Automatic}, {axisStart,
axisFinish}, {True, False}, {axisStart, 0}},
OptionValue["AxisType"] == "yAxis",
{{Automatic, {axisStart, axisFinish}}, {0, 1}, {False,
True}, {0,
axisStart}},
OptionValue["AxisType"] == "Both",
{Transpose@{axisStart, axisFinish}, {axisStart[],
axisFinish[]}, {True, True}, axisStart},
True,
Print["Invalid axis type"];
Abort[] (*If the option isn't one of the three axis types,
then quit the code*)];

axis = Plot[Null, {x, axisxrange[], axisxrange[]},
PlotRange -> axisplotrange, Axes -> axisaxes,
Evaluate@OptionValue["AxisOptions"]];

Show[plot,
Epilog -> { Evaluate@OptionValue["ExtraEpilog"],
Inset[Show[axis,
ImageSize ->
plotRangeRatio[axis, plot] printerPointsPlotRange[
plot] + (realImageDimensions[axis] -
printerPointsPlotRange[axis]),
AspectRatio -> (Last[#]/First[#] &)@(plotRangeRatio[axis,
plot] printerPointsPlotRange[plot])], {xpos, ypos},
insetpos, Automatic]}]
]


The function extraAxisPlot takes the following arguments,

1. A one-dimensional plot, upon which you wish to overlay an axis
2. A list of the initial and final values of the axis. In the case where both x and y axes are requested, these should be lists with 2 elements.
3. A list of the coordinates where the axis should start, in the absolute reference frame of the underlying plot.
4. Options, one option specifying which type of axis, and another which passes options on for the axis.

The output is a Graphics object. Here are three examples,

plot1 = Plot[5 Sin[x], {x, 32, 40}, GridLines -> Automatic,ImageSize -> 400]
{extraAxisPlot[plot1, {-2, 4}, {34, -2}],
extraAxisPlot[plot1, {107, 113}, {36, -2},
"AxisOptions" -> {AxesStyle -> Red}, "AxisType" -> "yAxis"],
extraAxisPlot[plot1, {{7, -3}, {11, 4}}, {36, -2},
"AxisOptions" -> {AxesStyle -> Red, BaseStyle -> 20},
"AxisType" -> "Both"]} In the underlying plot I added gridlines to show that the scales for the two axes overlap exactly - that is, one unit in the underlying plot is one unit in the extra axis. To have a different scale, I think it is necessary to change the Ticks for the axis,

extraAxisPlot[plot1, {-2, 4}, {34, -2},
"AxisOptions" -> {Ticks -> {{{-1.5, "Hello"}, {1.5, "world"}},
None}}] I'm a fan of using the CustomTicks package,

Needs["CustomTicks"];
extraAxisPlot[plot1, {-2, 4}, {34, -2},
"AxisOptions" -> {Ticks -> {LogTicks, None}}] One caveat is that it is necessary to set the size of the underlying image when defining it. If you try to resize the image with the mouse, it totally messes up the Inset.

This seems to work fine when exporting to vector or bitmap formats (I tested PNG and PDF). Any suggestions to improve the function are greatly appreciated, as well as examples that break the code.

Here's an approach similar to Jason's that also uses Inset, with the following differences:

1. The Inset graphic uses ImagePadding->0. This means that resizing the enclosing graphic will not mess up the location of the extra axis. This is the key difference between Jason's answer and mine. Instead of using a nonzero image padding, I extend the plot range of the inset so that all of the ticks are contained in the plot range.

2. The VerticalAxis and HorizontalAxis functions are defined as primitives (like Circle or Annulus).

3. The VerticalAxis and HorizontalAxis primitives need to know the entire plot range of the graphic in order to control the size of the ticks and the number of major/minor ticks to shoot for.

4. The axes and ticks styles are controlled using AxesStyle and TicksStyle as usual. A "Divisions" option is also supported, that specifies a goal for the number of major and minor ticks. With "Divisions"->Automatic, a goal is automatically set based on the ratio of the entire plot range of the enclosing graphic to the inset.

The syntax for both is:

VerticalAxis[location, {min, max}, plotRange]


where location specifies the axis origin, min and max specify the range of the axis, with min located at location, and plotRange specifies the plot range of the enclosing graphic. Options supported are Ticks, TicksStyle, AxesStyle and "Divisions". I will give the code at the end of this answer.

Here are Jason's examples using VerticalAxis and HorizontalAxis:

Plot[
5 Sin[x],
{x, 32, 40},
GridLines -> Automatic,
Epilog->HorizontalAxis[{34, -2}, {-2, 4}, {{32, 40}, {-5, 5}}]
] Plot[
5 Sin[x],
{x, 32, 40},
GridLines -> Automatic,
Epilog -> VerticalAxis[
{36, -2},
{107, 113},
{{32,40}, {-5,5}},
AxesStyle->Red,
"Divisions"->{8,5}
]
] Plot[
5 Sin[x],
{x, 32, 40},
GridLines -> Automatic,
Epilog -> {
HorizontalAxis[
{36.01, 1},
{7.01, 11},
{{32,40}, {-5,5}},
AxesStyle->{Red,FontSize->20},
"Divisions"->{4,5}
],
VerticalAxis[
{36,-2},
{-3,4},
{{32,40},{-5,5}},
"Divisions"->{8,5},
AxesStyle->Red, TicksStyle->FontSize->20
]
}
] Plot[
5 Sin[x],
{x, 32, 40},
GridLines -> Automatic,
Epilog -> HorizontalAxis[
{34,-2},
{0, 6},
{{32, 40}, {-5,5}},
Ticks->{{.5, "Hello"}, {3.5, "World"}}
]
] Plot[
5 Sin[x],
{x, 32, 40},
GridLines->Automatic,
Epilog->HorizontalAxis[
{34,-2},
{-2, 4},
{{32,40}, {-5,5}},
Ticks->ChartingScaledTicks[{Log10[#]&, Power[10,#]&}][-2,4,{6,6}]
]
] Note again, contrary to Jason's answer, resizing the graphics won't mess up the axes.

• I'm sorry but I can't find the code from Carl's answer. Nov 2, 2020 at 12:48
• I don't think it's there. Would love to see it though... Aug 28 at 18:59
• @mikemtnbikes By the time I realized I omitted the code, AxisObject arrived and it was pointless to add it. Aug 28 at 20:32

Here's my solution in Mathematica 13.0 using the AxisObject[] inside Epilog -> for a figure I've been working on (thus the code is more complex than needed...).


flux = 0;flux = 1;flux := (flux - flux)/2 + flux;
genotypeTicks := {{0, label}, {1/2, label}, {1, label}}
fluxTicks := {{flux, "0%"}, {flux, "50%"}, {flux, "100%"}}
phenotypeTicks := {{flux + 0.05, recessiveTrait}, {flux,
""}, {flux - 0.05, dominantTrait}}
concentrationTicks := {{0, "0%"}, {1/2, "50%"}, {1, "100%"}}

frameTicks := {{fluxTicks, phenotypeTicks}, {concentrationTicks,
None}};
frameLabel := {{fluxLabel, phenotypeLabel}, {concentrationLabel,
None}};
frame = {{True, True}, {True, False}}

recessiveTrait = "Wrinkled";
dominantTrait = "Round";
concentrationLabel = "Sbe1 Enzyme Concentration";
genotypeLabel = "Sbe1 Genotype";
fluxLabel = "Amylopectin Production";
phenotypeLabel = "Seed Shape"

label = "+/+"; label = "+/-"; label = "-/-";

ymax = 1;
km = 0.05;
curve[x_, km_, ymax_ : 1, n_ : 1] := ymax  x^n/(km + x^n)
plot = Plot[curve[x, km], {x, 0, 1},
PlotRange -> All,
Frame -> frame,
FrameTicks -> frameTicks,
FrameLabel -> frameLabel,
Epilog -> {Dashed, Line[{{1/2, 0}, {1/2, 1}}],
AxisObject[Line[{{0, -0.5}, {1, -0.5}}],
AxisLabel -> Placed[genotypeLabel, {Center, -1}],
AxisStyle -> Black,
Ticks -> genotypeTicks]},
AspectRatio -> 0.5,
PlotRangeClipping -> False] I am not sure if it's a bug or user error, but I have a hard time placing the label where I want, i.e. using Placed[genotypeLabel, {Center, -1}] gives the same behavior as Placed[genotypeLabel, {Center, 1}].