Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: two x axes for plot of same data

Tags:

julia

plotly

For certain functions it is convenient and commonplace to plot one dataset with two x axes. My example at hand is a function of the form f(T)=A*exp(-H/(R*T)), which is to be plotted with 1/T on the x axis and log(f) on the y axis. In this form, it conveniently appears as a straight line, but for ease of reading the actual temperature T instead of 1/T, it is common to put the corresponding T values on a second x axis in the same plot (which is then of course reversed and also not linearly spaced). How do I achieve this with Julia and Plotly?

Here is an example of the type of plot I try to make. For what it's worth, in Gnuplot the additional second (upper) x-axis would be created with set link x2 via 1./x inverse 1./x. conductivity vs. temperature

like image 731
TomR Avatar asked Sep 03 '25 04:09

TomR


1 Answers

For adding a second Y axis there is a twinx() method in the Plots.jl package. Unfortunately there is not twiny() method that could allow adding a secondary X axis.

However, you can take twinx() code and simply transpose it:

function twiny(sp::Plots.Subplot)
    sp[:top_margin] = max(sp[:top_margin], 30Plots.px)
    plot!(sp.plt, inset = (sp[:subplot_index], bbox(0,0,1,1)))
    twinsp = sp.plt.subplots[end]
    twinsp[:xaxis][:mirror] = true
    twinsp[:background_color_inside] = RGBA{Float64}(0,0,0,0)
    Plots.link_axes!(sp[:yaxis], twinsp[:yaxis])
    twinsp
end
twiny(plt::Plots.Plot = current()) = twiny(plt[1])

And now use it like this:

using Plots
plot(1:10,rand(10), label = "randData", ylabel = "Y axis",color = :red, legend = :topleft, grid = :off, xlabel = "Numbers Rand")
p = twiny()
plot!(p,5:15,log.(5:15), label = "log(x)", legend = :topright, box = :on, grid = :off, xlabel = "Log values")

enter image description here

like image 186
Przemyslaw Szufel Avatar answered Sep 05 '25 00:09

Przemyslaw Szufel