2

I want to include a ternary plot in a shiny app. I'm use package ggtern.

When I run the following code:

dd <- data.frame(x=c(3,1,5), y=c(45,29,10), z=c(10,45,94),
                ss=c(58,75,109))

ggtern(data=dd,
         aes(x=x,y=y,z=z)) +
  geom_mask() +
  geom_point() +
  Larrowlab("var1") + Tarrowlab("var2") + Rarrowlab("var3") +
  theme_showarrows() +
  theme(tern.axis.arrow.show=T)#,
          #tern.axis.text.show=F)

I get:

enter image description here

Inside a shiny app:

library(ggtern)
library(shiny)
## data ####
dd <- data.frame(x=c(3,1,5), y=c(45,29,10), z=c(10,45,94),
                ss=c(58,75,109))
################
runApp(

  ## UI ####
  list(ui = (basicPage(
    headerPanel("ternary test"),
    mainPanel(
      plotOutput("gg", click = "plot_click")
    )
  )),

  ## server ####
  server = function(input, output) {

    output$gg <- renderPlot({

      ggtern(data=dd,
             aes(x=x,y=y,z=z)) +
      geom_mask() +
      geom_point() +
      Larrowlab("var1") + Tarrowlab("var2") + Rarrowlab("var3") +
      theme_showarrows() +
      theme(tern.axis.arrow.show=T)#,
              #tern.axis.text.show=F)
    })

  }
  ))

I get this:

grafico

Why the differences? Is this a bug? Anyway around it?

Thanks, António

marxco
  • 121
  • 1
  • 3

1 Answers1

0

Using print(ggtern_plot), as suggested in the comments above does not translate plot clicks properly and does not scale the plot.

ggtern does not work with shiny well because ggtern overloads plot.ggplot but shiny does not use the overloaded function. I managed to fix the plot this way:

custom_print.ggplot <- function(x) {
    ggtern:::ggint$set_last_plot(x) # this is line needed by ggtern
    # based on ggplot2:::custom_print.ggplot
    grid::grid.newpage()

    data <- ggplot_build(x)
    gtable <- ggplot_gtable(data)
    grid::grid.draw(gtable)
    invisible(data)
    structure(list(
        build = data,
        gtable = gtable
    ), class = "ggplot_build_gtable")
}
assignInNamespace("custom_print.ggplot", custom_print.ggplot, "shiny")