plotly / plotly.R

An interactive graphing library for R
https://plotly-r.com
Other
2.56k stars 626 forks source link

Encoding problems using ggplot2, Shiny and Plotly #127

Closed JuanGaleano closed 8 years ago

JuanGaleano commented 10 years ago

Hi, I'm trying to create an app for a website using R, ggplot2, Shiny and Plotly, and I'm facing two different problems. I would really appreciate any help or advice.

1) As I live in Spain I have to deal with a number of special symbols (eg:Á, á, à, é, É, ñ, ï, etc). I've solved the issue on the shiny part of the app, but I still have problems with titles on the plotly plots. 2) The aes parameters (axes ticks, labels, fonts) on plotly plots are not responding to those on the code (using ggplot2).

The expected look of the plotly plots it's available by downloading them as png files.

Here the reproducible code (pick Agrón as Municipality)

Server file

library(shiny)
library(plotly)
library(ggplot2)
library(scales)

load(url('http://gedemced.uab.cat/images/ANDALUCIA.Rdata'))

# Define a server for the Shiny app

shinyServer(function(input, output) {  
  output$ComposicionPlot <-renderUI({ 
    Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
    comp<- ggplot(data=Mun, aes(x=YEAR, y=POP, fill=ORIGIN)) + 
            geom_bar(stat="identity", colour="black")+
            scale_x_continuous(breaks=seq(2000,2013, 2))+
            ggtitle(paste("Population composition",input$MUN2, sep=": "))+
            scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                                labels=c("Spanish-born", "Foreign-born"))+
            theme(plot.title = element_text(lineheight=5.6, size=15, face="bold"),
                  legend.title = element_blank(),
                  legend.text = element_text(colour="black", size = 10),
                  legend.position="bottom",
                  legend.background = element_rect(fill="#FFFFFF"),
                  axis.title.x = element_blank(),
                  axis.text.x  = element_text(angle = 0,vjust=0.5, size=10,colour="black",face="bold"),
                  axis.title.y = element_text(face="bold", colour="black", size=10),
                  axis.text.y  = element_text( vjust=0.5, size=10,colour="black",face="bold"),
                  plot.background = element_rect(fill = "#FFFFFF"))+
            ylab("Population")

    py <- plotly(username="Username", key="whatever")  # Open Plotly connection

    res <- py$ggplotly(comp, kwargs=list(filename="Prueba", 
                                           fileopt="overwrite", # Overwrite plot in Plotly's website
                                           auto_open=FALSE))

    tags$iframe(src=res$response$url,
                frameBorder="0",  # Some aesthetics
                height=400,
                width=650)

  })
  output$ComposicionPlot2 <-renderUI({ 
    Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
    comp<- ggplot(data=Mun, aes(x=YEAR, y=PROP, fill=ORIGIN)) + 
      geom_bar(stat="identity", colour="black")+
      scale_x_continuous(breaks=seq(2000,2013, 2))+
      scale_y_continuous(labels = percent)+
      ggtitle(paste("Population composition",input$MUN2, sep=": "))+
      scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                          labels=c("Spanish-born", "Foreign-born"))+
      theme(plot.title = element_text(lineheight=5.6, size=15, face="bold"),
            legend.title = element_blank(),
            legend.text = element_text(colour="black", size = 10),
            legend.position="bottom",
            legend.background = element_rect(fill="#FFFFFF"),
            axis.title.x = element_blank(),
            axis.text.x  = element_text(angle = 0,vjust=0.5, size=10,colour="black",face="bold"),
            axis.title.y = element_text(face="bold", colour="black", size=10),
            axis.text.y  = element_text( vjust=0.5, size=10,colour="black",face="bold"),
            plot.background = element_rect(fill = "#FFFFFF"))+
      ylab("Percentage")

    py <- plotly(username="Username", key="whatever")  # Open Plotly connection

    res <- py$ggplotly(comp, kwargs=list(filename="Prueba2", 
                                         fileopt="overwrite", # Overwrite plot in Plotly's website
                                         auto_open=FALSE))

    tags$iframe(src=res$response$url,
                frameBorder="0",  # Some aesthetics
                height=400,
                width=650)

  })
  output$downloadPlot <- downloadHandler(
    filename = function() { paste(input$MUN2, '.png', sep='') },
    content = function(file) {
      png(file,width = 600, height = 400)
      Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
      print(ggplot(data=Mun, aes(x=YEAR, y=POP, fill=ORIGIN)) + geom_bar(stat="identity", colour="black")+
              scale_x_continuous(breaks=seq(2000,2013, 1))+
              ggtitle(paste("Population composition",input$MUN2, sep=": "))+
              scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                                  labels=c("Spanish-born", "Foreign-born"))+
              theme(plot.title = element_text(lineheight=5.6, size=20, face="bold"),
                    legend.title = element_blank(),
                    legend.text = element_text(colour="black", size = 20),
                    legend.position="bottom",
                    legend.background = element_rect(fill="#FFFFFF"),
                    axis.title.x = element_blank(),
                    axis.text.x  = element_text(angle = 90,vjust=0.5, size=20,colour="black",face="bold"),
                    axis.title.y = element_text(face="bold", colour="black", size=20),
                    axis.text.y  = element_text( vjust=0.5, size=20,colour="black",face="bold"),
                    plot.background = element_rect(fill = "#FFFFFF"))+
              ylab("Population"))
      dev.off()
    })
  output$downloadPlot2 <- downloadHandler(
    filename = function() { paste(input$MUN2, '.png', sep='') },
    content = function(file) {
      png(file,width = 600, height = 400)
      Mun <- ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ]
      print(ggplot(data=Mun, aes(x=YEAR, y=PROP, fill=ORIGIN)) + geom_bar(stat="identity", colour="black")+
              scale_x_continuous(breaks=seq(2000,2013, 1))+
              scale_y_continuous(labels = percent)+
              ggtitle(paste("Population composition",input$MUN2, sep=": "))+
              scale_fill_discrete(breaks=c("Spanish-born", "Foreign-born"),
                                  labels=c("Spanish-born", "Foreign-born"))+
              theme(plot.title = element_text(lineheight=5.6, size=20, face="bold"),
                    legend.title = element_blank(),
                    legend.text = element_text(colour="black", size = 20),
                    legend.position="bottom",
                    legend.background = element_rect(fill="#FFFFFF"),
                    axis.title.x = element_blank(),
                    axis.text.x  = element_text(angle = 90,vjust=0.5, size=20,colour="black",face="bold"),
                    axis.title.y = element_text(face="bold", colour="black", size=20),
                    axis.text.y  = element_text( vjust=0.5, size=20,colour="black",face="bold"),
                    plot.background = element_rect(fill = "#FFFFFF"))+
              ylab("Percentage"))
      dev.off()
    })
  output$downloadData <- downloadHandler(

    # This function returns a string which tells the client
    # browser what name to use when saving the file.
    filename = function() {
      paste(input$MUN2, input$filetype, sep = ".")
    },

    # This function should write data to a file given to it by
    # the argument 'file'.
    content = function(file) {
      sep <- switch(input$filetype, "csv" = ",", "txt" = "\t")

      # Write to a file specified by the 'file' argument
      write.table(ANDALUCIA[ANDALUCIA$MUN2 %in% input$MUN2, ], file, sep = sep,
                  row.names = FALSE)
    }
  )
})

ui file

load(url('http://gedemced.uab.cat/images/ANDALUCIA.Rdata'))
# Define the overall UI
shinyUI(fluidPage(
  titlePanel("Autonomous Community: ANDALUSIA"),

  sidebarPanel(
    selectInput("MUN2", "Municipality", 
                choices=unique(ANDALUCIA$MUN2)),

    downloadButton('downloadPlot', 'Download plot 1'),
    downloadButton('downloadPlot2', 'Download plot 2'),
    radioButtons("filetype", "File extension:",
                 choices = c("csv", "txt")),
    downloadButton('downloadData', 'Download data'),
    # HTML info
    div(style = "margin-top: 10px; margin-left: 0px; width: 200px; ", HTML("Elaboration:")),
    div(style = "margin-top: 1px;margin-left: 0px; ", HTML("<a href='http://gedemced.uab.cat/'><img style='width: 150px;' src='http://gedemced.uab.cat/images/logo-GEDEM-01peque.png'/>")),
    div(style = "margin-top: 5px;", HTML("Data: <a href='http://www.ine.es/'>INE - Instituto Nacional de Estadí­­stica</a>"))

  ),    
  mainPanel( 
    htmlOutput("ComposicionPlot"),
    htmlOutput("ComposicionPlot2")
  )
  ))
cpsievert commented 8 years ago

I don't think this should be a problem any longer. Please feel free to reopen if it is.