ramnathv / rCharts

Interactive JS Charts from R
http://rcharts.io
Other
1.19k stars 654 forks source link

Leaflet Map and nvd3 chart display problem in one shiny page #388

Open wmilos opened 10 years ago

wmilos commented 10 years ago

Hi, guys, I'm a new shiny user, I'm trying to reproduce M.Ramnathv's bike share app with some modification.

When I tried to put one Leaflet Map and one NVD3 chart in one same shiny page,

  1. the markers in the Leaflet map can't be displayed
  2. the dimension of charts is out of control

Anyone can tell me why these happened and how to fix, please?

Here is my data and code :

## global.r

require(shiny)
require(rCharts)

direc <- "E:\\daily_heat_map\\"
options(stringsAsFactors = F)

setwd("E:\\rShiny\\myShiny")

#Import data and preparation for Leaflet Map

df <- read.csv(paste0(direc,"city_sale.csv"))

df <- na.omit(df)

province_order <- aggregate(nb_order  ~ province_id + province_name + province_lat + province_lon, data = df, FUN = sum)

province_cust <- aggregate(nb_cust  ~ province_id + province_name + province_lat + province_lon, data = df, FUN = sum)

province_order <- cbind(province_order,index='order')
province_cust <- cbind(province_cust,index='customer')

names(province_cust)[5] <- "Quantity"
names(province_order)[5] <- "Quantity"
province <- rbind(province_order,province_cust)

####

hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
##  ui.r

shinyUI(fluidPage(

  tags$head(tags$link(rel='stylesheet', type='text/css', href='styles.css')),

  showOutput("myChart",lib = "leaflet"),

  fluidRow(

    column(3,
      h4('Select a province'),
      selectInput("province", "", 
                  choices = c(111,112,113,114,115,121,122,123,131,132,133,134,
                              135,136,137,141,142,143,144,145,146,150,151,152,
                              153,154,161,162,163,164,615)),
      #tags$style(type='text/css', "#province { width: 600px; }"),
      submitButton("Update View")
      ),

    column(5, offset=1,
           h2('Shiny first try, 2014/03/25'),
           HTML(paste(
               'The map is centered at center_$lat, center_$lon,',
               'with a zoom level of 5.'
             ))
            )
          ),
  hr(),

  fluidRow(
    column(3,
           h4("Point of View"),
           selectInput(
             inputId = 'order_or_customer',
             label = 'Order/Customer Quantity',
             choices = c('order','customer'),
             selected = 'order'
             )
           ),
    column(4,offset=1,
           h4("Province Detail"),
           showOutput("myChart2",lib='nvd3')
      )
  ),
  hr()

))
## server.r

shinyServer(function(input, output) {

    Map_Data <- reactive({

      temp <- subset(province,index==input$order_or_customer)

      color <- ifelse(input$order_or_customer=='order',"Blues","Reds")

      fillColor <- cut(
        as.numeric(temp$Quantity)/max(as.numeric(temp$Quantity)), 
        breaks = c(0, 0.03, 0.05, 0.10, 0.2, 1), 
        labels = brewer.pal(5, color),
        include.lowest = TRUE
      ) 

      radius <- round(sqrt(as.numeric(temp$Quantity)/50))

      temp <- cbind(temp,fillColor,radius)[-6]

      mydata <- toJSONArray2(na.omit(temp), json = F, names = F)

      rename <- function(x){
        names(x) <- c("province_id","province_name","latitude","longitude","count","fillColor","radius")
        return(x)
      }

      mydata <- lapply(mydata,rename)

      mydata <- lapply(mydata, function(station){within(station, { 
        popup = iconv(whisker::whisker.render(
          '<b>{{province_name}}</b><br>
          <b>Quantity: </b> {{count}}
         '
        ))})
      })

      mydata

    })

    geo_center <- reactive({

      temp <- subset(province,index==input$order_or_customer)

      getCenter <- function(x){
        lat = mean(x$province_lat)
        lon = mean(x$province_lon)
        return(list(lat = lat, lon = lon))
      }

      center_ <- getCenter(temp)
      center_

    })

  # =======  Leaflet Map ======================

  output$myChart <- renderMap({

    # ====== Point chart 

      L1 <- Leaflet$new()
      L1$tileLayer(provider = "Stamen.TonerLite")
      L1$set(width = 1600, height = 400)
      L1$setView(c(geo_center()$lat, geo_center()$lon), 5)
      L1$geoJson(toGeoJSON(Map_Data()), 

        onEachFeature = "#! function(feature, layer){
        layer.bindPopup(feature.properties.popup)
        } !#",        
        pointToLayer =  "#! function(feature, latlng){
        return L.circleMarker(latlng, {
        radius: feature.properties.radius || 4,
        fillColor: feature.properties.fillColor || 'red',    
        color: '#000',
        weight: 1,
        fillOpacity: 0.8
        })
        } !#" )
      L1$enablePopover(TRUE)
      L1$fullScreen(TRUE)
      return(L1)
  })

  # ========NVD3 Charts =========

  output$myChart2 <- renderChart2({

    n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
    #n1$set(width = 1600, height = 400)
    return(n1)
  })
})

I have put the data in Dropbox, here is the link:https://www.dropbox.com/s/43uixde01eil2bd/city_sale.csv

I'm so sorry for my catastrophic typography!

Merci mille fois!!

ramnathv commented 10 years ago

I believe the issue might be with the CSS across the two charts interacting. I will try and take a look at this later this week.

wmilos commented 10 years ago

Thank you very much in advance, M.Ramnathv!

nickponline commented 10 years ago

I think I have the same issue.

timelyportfolio commented 10 years ago

Not at the computer but see if #233 or http://stackoverflow.com/questions/19812465/rcharts-and-rickshaw-slider-disappears-from-rickshaw-chart-when-a-datatable-is help. I think there is another answer that shows how to do in shiny.

abrel commented 10 years ago

Hi all,

I am also experiencing the same issue. I had a look at the link timelyportfolio kindly pointed out however I am not able to adapt it for shiny. Any tips on how I could do that?

Many thanks!

Fooourche commented 9 years ago

I everybody, i'm experiencing the same pb, my polygons disapear when using nvd3 lib of rCharts. Do u have any solution ?

Thanks Fabien

ramnathv commented 9 years ago

See the workaround posted here in the comments. It happens due to CSS conflict between Leaflet and NVD3. Unfortunately, there is no generic way to resolve these things.

Fooourche commented 9 years ago

Thanks you for the answear I'm going to change of library

Fabien

ghost commented 9 years ago

@wmilos could you please provide working link to your data file? I would like to reproduce your code. Thank you very much.

colemand77 commented 9 years ago

@ramnathv , is it fair to conclude from your comment above that there is not now, nor will there ever be, a way to use NVD3 and Leaflet in the same ShinyApp (for ever and ever, Amen)?

Despite this, I think your rCharts library is bad to the bone. Rockstar. If rCharts went on tour it would leave a trail of impregnated groupies and trashed hotel rooms. It would check itself into rehab and emerge a year later for a reunion tour with ggplot2 opening for rCharts. I don't know enough to hold your tool bag, but if I could - I would.
tbenschop commented 8 years ago

@ramnathv , the solution in that SO post works, but messes up the NVD3 plot. Any other workarounds? Or can we set the 100% width and height somewhere outside the css?

bogdanrau commented 8 years ago

Also waiting on a solution for this. Would appreciate any alternative to the CSS modification.

elwan3 commented 8 years ago

@ramnathv @timelyportfolio I have the same issue. http://stackoverflow.com/questions/36732711/shiny-leaflet-map-is-not-working-with-rcharts Any suggestions would be appreciated.

timelyportfolio commented 8 years ago

I'm sorry. I know this CSS conflict has been quite troublesome and annoying. I have I think fixed in https://github.com/ramnathv/rCharts/pull/706#event-634734584.

In general, we do plan to rebuild rCharts on top of the much more robust htmlwidgets infrastructure, and many of these problems will be solved. There are many lingering problems and issues that we can hopefully address in the rebuild.

copaah commented 8 years ago

Do people still face this issue?

qiwei-li commented 8 years ago

@MarcoDalFarra Update your rchart library. The problem should be fixed.

remyzum commented 7 years ago

Hi Everybody, it looks like I have the same kind of problem as described above. It seems that there is still a conflict between Leaflet and rCharts. Please see my yesterday's question and reproducible code on stackoverflow : http://stackoverflow.com/questions/39722040/r-shiny-clusteroptions-not-displayed-on-a-tabpanel-conflict-with-rcharts Any advice will be much appreciated , thank you !

remyzum commented 7 years ago

Problem solved : I had to use htmlOutput instead of showOutput in the ui.R. The clusters are now displayed correctly on the first tabPanel.