Search code examples
rggplot2data-visualizationggtern

ggtern: intersection between line (geom_segment) and smoothed data (geom_smooth_tern)


im currently working on visualization of an evaporation experiment. I've plotted a ternary phase diagram (NaCl-Na2SO4-H2O) with ggtern and data based on phreeqc simulation. Phase boundaries (red/blue) are smoothed data points (geom_smooth_tern).

> geom_smooth_tern(data=dataTernNaCl, aes(x=NaCl, y=H2O, z=Na2SO4), method = loess, se = FALSE, color = "blue")

#Dataframe
> select(dataTernNaCl, NaCl, Na2SO4, H2O)[324:329,]
# A tibble: 6 x 3
   NaCl     Na2SO4       H2O
  <dbl>      <dbl>     <dbl>
1 0.2503361 0.03098092 0.7186830
2 0.2502058 0.03123192 0.7185623
3 0.2500746 0.03148678 0.7184386
4 0.2499421 0.03174650 0.7183114
5 0.2498056 0.03201021 0.7181842
6 0.2496680 0.03227777 0.7180542

Given that phase diagram, I want to visualize the evaporation path (reduction of H2O) from a certain point P1 (based on experimental data).

Straight reduction of H2O is perfectly describable as a line between 2 points. Im using geom_segment.

I need to find the intersection of the evaporation line with the phase boundaries to finally draw the line from P1 to the point of intersection.

Plot

Greetings, Christian


Solution

  • Based on @Onyambu advise:

    key was to limit optimise() inside the range of the data im giving to the model for the blue line (modelPhaseboundaryNaCl).

    #function evaporation line between from starting point | input = NaCl
    funEvapLine = function(x){
    y <- messwerteTern
    m <- (y$Ausgang_Na2SO4Ende-y$Ausgang_Na2SO4)/(y$Ausgang_NaClEnde-y$Ausgang_NaCl)
    n <- y$Ausgang_Na2SO4/(y$Ausgang_NaCl * m)
    m*x+n-1
      }
    
    #function NaCl phase boundary | only works in NaCl range | input = NaCl
    modelPhaseBoundaryNaCl <- loess(Na2SO4 ~ NaCl, data=dataTernNaCl)
    funNaClBorder <- function(x)predict(modelPhaseBoundaryNaCl, data.frame(NaCl = x))
    
    #function Intersection EvapLine and NaCl phase boundary | input = NaCl | output = NaCl
    NaClmin <- min(dataTernNaCl$NaCl)
    NaClmax <- max(dataTernNaCl$NaCl)
    g <- function(x)(funNaClBorder(x) - funEvapLine(x))
    intersectionNaCl <- optimise(function(x)abs(g(x)), c(NaClmin,NaClmax))$min
    intersectionNa2SO4 <- funEvapLine(intersectionNa2SO4)
    intersectionH2O <- 1-(intersectionNaCl+intersectionNa2SO4)
    

    intersection