Hello,

Does anyone know how to make a plot with a second x-axis (on the top edge of the plot). I’d like to make values of the second x-axis a user supplied function of values on the primary x-axis.

Thanks,

Joe

Hello,

Does anyone know how to make a plot with a second x-axis (on the top edge of the plot). I’d like to make values of the second x-axis a user supplied function of values on the primary x-axis.

Thanks,

Joe

Welcome! Are you using Plots.jl or Makie.jl?

Hello! I generally use Plots.jl but have used Makie.jl a bit too.

With Plots.jl check `twiny()`

:

Example:

```
using Plots
x = 1:10000
plot(x, log.(x), c=:blue, x_foreground_color_axis=:blue, x_foreground_color_text=:blue)
p2 = twiny()
plot!(p2, log.(x/2), 2*log.(x), c=:red, x_foreground_color_axis=:red, x_foreground_color_text=:red)
```

Thanks. I should have been more specific. I’m trying to plot just one trace. The bottom x-axis should be in the original units of x. The top x-axis should be in units of some function of x, say log(x).

NB: removed proposal, as well pointed out by @jules, the f(x) scale was not correct.

That doesn’t look correct, a log scale and a linear scale can’t both have ticks at equal distances if they are about the same data.

If you want to use the same ticks as the lower axis, just transformed, you generally won’t get nice numbers on the log scale. If the upper axis can have different tick positions than the lower one, there are more choices.

Yes, I’m just trying to do one plot say for y = x. Then have the top x-axis be a function of the bottom x-axis. For example, if the transformation function is 1/x and the bottom x is 5, the top x would be .2.

Thanks @jules, indeed there is a problem.

I remember a few years ago I was looking for this feature and at that time I had to use PyPlot.jl. See the PyPlot solution here, where the function f(x) must be monotonic.

Thank you! It’s the empirical PyPlot solution I was looking for.

Here a simple solution with Plots.jl, really simple:

```
using Plots; gr(dpi=600)
x = 1:1000; y = log.(x)
f(x) = 1/x
p1 = plot(x, y, c=:blue, xlabel="x", ylabel="y")
xt = xticks(p1)[1][1]
str2 = string.(round.(f.(xt), digits=5))
plot!(twiny(), x, y, c=:blue, xticks=(xt, str2), xlabel="f(x) scale")
```

Exactly what I was looking for. Thank you.

1 Like