Coder Social home page Coder Social logo

r-user-guide's Introduction

r-user-guide's People

Contributors

chriddyp avatar cpsievert avatar etpinard avatar mkcor avatar pedrodz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

r-user-guide's Issues

Using Plotly in shinydashboard -- Buttons too large to see plot

Hello.

I'm trying to use plotly in R's shinydashboard package. Whenever I load the app and try to interact with the plot I just made, the buttons usually on the top right of the plot become so large that I can't even see/interact with said plot.

So far, I've only used the plotly's shiny tutorial (https://plot.ly/r/shiny-tutorial/), the movie ratings one, in my shinydashboard app.

Here is what my app looks like when I try to interact with the plot:
plotly huge buttons

Here is my ui code (the renderPlotly can be found at the bottom of the code):

library(ggplot2)
library(plyr)
library(rCharts)
library(shiny)
library(xtable)
library(shinythemes)
library(shinydashboard)
library(dplyr)
library(plotly)
PopData <- read.csv("CountyPopLong.csv", header=T)
ChangeData <- read.csv("CountyChangeLong.csv", header=T)
CountyPop <- read.csv("CountyPopWide.csv", header=T)
CountyChange <- read.csv("CountyChangeWide.csv", header=T)
CntyInfo <- read.csv("CntyCensusInfo.csv", header=T)
CityPop <- read.csv("CityData.csv", header=T)
CityPopLong <- read.csv("CityPop.csv", header=T)
CityChange <- read.csv("CityChangeWide.csv", header=T)
CityChangeLong <- read.csv("CityChangeLong.csv", header=T)
CityInfo <- read.csv("CityCensusInfo.csv", header=T)
TwpInfo <- read.csv("TwpCensusInfo.csv", header=T)
TwpPop <- read.csv("TownshipPopWide.csv", header=T)
TwpPopLong <- read.csv("TownshipPopLongWithCounty.csv", header=T)
TwpChange <- read.csv("TwpChangeWide.csv", header=T)
TwpChangeLong <- read.csv("TwpChangeLong.csv", header=T)
MHIdata <- read.csv("CountyMHILong.csv", header=T)
PCIdata <- read.csv("CountyPCILong.csv", header=T)
CityACS <- read.csv("CityACSLong.csv", header=T)
TwpACS <- read.csv("TwpACSLong.csv", header=T)
CountyBGLong <- read.csv("CountyBG2000to2010long.csv", header=T)
CityBGLong <- read.csv("CityBG2000to2010long.csv", header=T)
TwpBGLong <- read.csv("TwpBrainGain2000to2010long.csv", header=T)
CountyBG90Long <- read.csv("CountyBG1990to2000long.csv", header=T)
CityBG90Long <- read.csv("CityBG1990to2000long.csv", header=T)
TwpBG90Long <- read.csv("TwpBrainGain1990to2000long.csv", header=T)
options(RCHART_WIDTH=500, RCHART_HEIGHT=500)

dashboardPage(
header <- dashboardHeader(

  title = "CST Datapage"
  ),



  dashboardSidebar(
    sidebarMenu(
      sidebarMenu(
        menuItem("County Table", tabName="County-Table"),

        menuItem("Township", tabName="Township",
          menuSubItem("Table", tabName = "Table"),
          menuSubItem("Chart", tabName = "Chart")
      ),

        menuItem("Plotly Stuff", tabName = "Plotly-Stuff")
    )),

  tags$head(

    tags$style(HTML("
                    .sidebar{height: 90vh; overflow-y: auto; }
                    .dataTables_wrapper { overflow-x: scroll; }
                    .rChart {height: 500px, width: 100%}
                    "))
  )  

  ),

  dashboardBody(
  tabItems(
  tabItem(tabName =  "Table",

          tabBox(

          title = "Township Table",
          id= "TwpPopTable", height = "5000px", width = "1000px",
          tabPanel("Download Data", 
          fluidPage(
                          absolutePanel(draggable=F, top=125, left = 250, width = "40.2%",
                                        sidebarPanel(
                                          helpText("The township data is organized by county. To view a specific township�s population, first select the county it is located. You can compare multiple townships by holding down �CTRL� while selecting your desired counties."),
                                          selectInput("County4", 
                                                      "Select a County:", 
                                                      c("All", 
                                                        unique(as.character(TwpPop$County))),
                                                      selected = "All",
                                                      multiple = TRUE
                                                      #                                                                               , selectize = FALSE
                                          ),
                                          helpText("To download the full dataset in .csv format, click the button below. Customized data can also be copied and pasted into an Excel spreadsheet with the formatting intact."),
                                          downloadButton('twpPopDownload', label = "Download Data"),
                                          width = 12)))),
          tabPanel("Table", 
                          mainPanel(dataTableOutput(outputId="TwpPopTable"),
                                    p("Source: U.S. Census Bureau, Decennial Censuses 1900-2010"))


           ))),


  tabItem((tabName = "Chart"),

            fluidRow(  
              column(width=5,
                  box(   
                  showOutput("TwpPopChart", "nvd3"), status= "primary",
                  p("Source: U.S. Census Bureau, Decennial Censuses 1900-2010")
                  , widths = c(1, 10))), 

              absolutePanel(draggable=T, top=200, left = 1000, width = "20%",
                            helpText("The township data is organized by county. To view a specific township�s population, first select the county it is located. You can compare multiple townships by holding down �CTRL� while selecting your desired counties. Then select the communities you want to compare by clicking on the legend."),
                            selectInput("County5", 
                                        "Select a County:", 
                                        c(unique(as.character(TwpPopLong$County))),
                                        selected = "Aitkin",
                                        multiple = TRUE
                                        #                                                                               , selectize = FALSE
                            )))

  ),

  tabItem(
    (tabName = "County-Table"),

          h2("Ayyyyyy")

          ),



  tabItem(
    (tabName = "Plotly-Stuff"),

      fluidRow( 
      mainPanel(plotlyOutput("trendPlot", width="100%")),


      sliderInput("bins", "Numbner of bins:", min=1,max=50,value=10))
  )),

  #Below is for colors display of the 

  tags$head(tags$style(HTML('
            .skin-blue .main-header .logo{
              font-family: Georgia, Times, "Times New Roman", serif;
              font-weight: bold;
              font-size: 24px;
              color: #FFFF1C;
            }

            .skin-blue .main-header .logo{
              background-color: #FF9900;
            }

            .skin-blue .main-header .navbar{
              background-color: #FF9900;
            }

            .skin-blue .main-sidebar{
              background-color: #FF9900;
            }

            .skin-blue .main-sidebar{
              font-family: Georgia, Times, "Times New Roman", serif;
              font-weight: bold;
              font-size: 12px;
              color:#FFFF1C;
            }

            .skin-blue .main-sidebar .sidebar .sidebar-menu .active a{
              color: #FFFF1C;
            }

            .skin-blue .main-header .logo:hover{
              background-color: #FF9900;
            }

            ')


  ))

))

server code:

library(ggplot2)
library(plyr)
library(rCharts)
library(shiny)
library(xtable)
library(RColorBrewer)
library(shinythemes)
library(shinydashboard)
library(dplyr)
library(plotly)
PopData <- read.csv("CountyPopLong.csv", header=T)
ChangeData <- read.csv("CountyChangeLong.csv", header=T)
CountyPop <- read.csv("CountyPopWide.csv", header=T)
CountyChange <- read.csv("CountyChangeWide.csv", header=T)
CntyInfo <- read.csv("CntyCensusInfo.csv", header=T)
CityPop <- read.csv("CityData.csv", header=T)
CityPopLong <- read.csv("CityPop.csv", header=T)
CityChange <- read.csv("CityChangeWide.csv", header=T)
CityChangeLong <- read.csv("CityChangeLong.csv", header=T)
CityInfo <- read.csv("CityCensusInfo.csv", header=T)
TwpInfo <- read.csv("TwpCensusInfo.csv", header=T)
TwpPop <- read.csv("TownshipPopWide.csv", header=T)
TwpPopLong <- read.csv("TownshipPopLongWithCounty.csv", header=T)
TwpChange <- read.csv("TwpChangeWide.csv", header=T)
TwpChangeLong <- read.csv("TwpChangeLong.csv", header=T)
MHIdata <- read.csv("CountyMHILong.csv", header=T)
PCIdata <- read.csv("CountyPCILong.csv", header=T)
CityACS <- read.csv("CityACSLong.csv", header=T)
TwpACS <- read.csv("TwpACSLong.csv", header=T)
CountyBGLong <- read.csv("CountyBG2000to2010long.csv", header=T)
CityBGLong <- read.csv("CityBG2000to2010long.csv", header=T)
TwpBGLong <- read.csv("TwpBrainGain2000to2010long.csv", header=T)
CountyBG90Long <- read.csv("CountyBG1990to2000long.csv", header=T)
CityBG90Long <- read.csv("CityBG1990to2000long.csv", header=T)
TwpBG90Long <- read.csv("TwpBrainGain1990to2000long.csv", header=T)
options(RCHART_WIDTH=800, RCHART_HEIGHT=600)

function(input, output) {

output$table <- renderDataTable(iris)

set.seed(122)
histdata <- rnorm(500)

######################## POPULATION OUTPUTS ########################
output$PopTable <- renderDataTable({
  data <- CountyPop
  if (input$County != "All"){
    data <- data[data$County %in% input$County,]
  }
  data
}, options =list(aoColumnDefs = list(list(sClass="alignCenter",aTargets=c(list("_all")) )),  pageLength=10))

output$PopChart <- renderChart({
  names(PopData) = gsub("\\.", "", names(PopData))
  n1 <- nPlot(Population ~ Year, data = PopData, group = "County", type = 'lineChart')
  n1$addParams(dom = 'PopChart')
  n1$yAxis(axisLabel = "Population", width = 62)      
  n1$xAxis(axisLabel = "Year")
  n1$chart(forceY = c(0, 1))
  n1$xAxis(tickValues=c(1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010))
  return(n1)
})

output$countyPopDownload <- downloadHandler(
  filename = function() { paste('MNCountyPopData', '.csv', sep='') },
  content = function(file) {
    write.csv(PopData, file)
  }) 

output$CityPopTable <- renderDataTable({
  data <- CityPop
  if (input$County2 != "All"){
    data <- data[data$County %in% input$County2,]
  }
  data
}, options =list(aoColumnDefs = list(list(sClass="alignCenter",aTargets=c(list("_all")) )),  pageLength=10))

output$CityPopChart <- renderChart({
  var <- reactive({input$County3})
  DF <- subset(CityPopLong, County %in% var())
  names(DF) = gsub("\\.", "", names(DF))
  n2 <- nPlot(Population ~ Year, data = DF, group = "Name", type = 'lineChart')
  n2$addParams(dom = 'CityPopChart')
  n2$yAxis(axisLabel = "Population", width = 62)      
  n2$xAxis(axisLabel = "Year")
  n2$xAxis(tickValues=c(1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010))
  n2$chart(forceY = c(0, 1))
  return(n2)
})

output$cityPopDownload <- downloadHandler(
  filename = function() { paste('MNCityPopData', '.csv', sep='') },
  content = function(file) {
    write.csv(CityPop, file)
  }) 

output$TwpPopTable <- renderDataTable({
  data <- TwpPop
  if (input$County4 != "All"){
    data <- data[data$County %in% input$County4,]
  }
  data
}, options =list(aoColumnDefs = list(list( sClass="alignCenter",aTargets=c(list("_all"))  )),  pageLength=10))


renderChart_pct <- function(expr, env = parent.frame(), quoted = FALSE) {
  func <- shiny::exprToFunction(expr, env, quoted)
  function() {
    rChart_ <- func()
    cht_style <- sprintf("<style>.rChart {width: %s; height: %s} </style>",
                         #### change these here to desired %
                         "100%", "100%")
    cht <- paste(capture.output(rChart_$print()), collapse = '\n')
    HTML(paste(c(cht_style, cht), collapse = '\n'))
  }
}

output$TwpPopChart <- renderChart({
  var <- reactive({input$County5})
  DF <- subset(TwpPopLong, County %in% var())
  names(DF) = sub("\\.", "", names(DF))
  n2 <- nPlot(Population ~ Year, data = DF, group = "Name", type = 'lineChart')
  n2$addParams(dom = 'TwpPopChart')
  n2$yAxis(axisLabel = "Population", width = 62)      
  n2$xAxis(axisLabel = "Year")
  n2$xAxis(tickValues=c(1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010))
  n2$chart(forceY = c(0, 1))
  n2$chart(height=500)
  n2$set(width=500)
  return(n2)
})

output$twpPopDownload <- downloadHandler(
  filename = function() { paste('MNTownshipPopData', '.csv', sep='') },
  content = function(file) {
    write.csv(TwpPop, file)
  })

######################## POPULATION CHANGE OUTPUTS ########################

output$ChangeTable <- renderDataTable({
  data <- CountyChange
  if (input$County6 != "All"){
    data <- data[data$County %in% input$County6,]
  }
  data
}, options =list(aoColumnDefs = list(list(sClass="alignCenter",aTargets=c(list("_all"))  )),  pageLength=10))  

output$ChangeChart <- renderChart({
  names(ChangeData) = gsub("\\.", "", names(ChangeData))
  n3 <- nPlot(PercentChange ~ Year, data = ChangeData, group = "County", type = 'lineChart')
  n3$addParams(dom = 'ChangeChart')
  #     n3$yAxis(tickValues=function(d) {return(d + "%")})
  ##    ^infinite recursion
  #     n3$yAxis(tickFormat="#!function(d) {return d3.format('%Y'));}!#" )
  ##    ^all axis values gone, chart turns static
  #     n3$yAxis(labelType='percent')
  ##     ^ only for pie charts
  #     n3$yAxis(tickFormat=function(d) { return(parseInt(d, 10) + "%")})
  ##     ^ "could not find function 'd3.format'"
  n3$yAxis(axisLabel = "Percent Change from Previous Decade", width = 62)      
  n3$xAxis(axisLabel = "Year")
  n3$xAxis(tickValues=c(1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010))
  return(n3)
})

output$countyChangeDownload <- downloadHandler(
  filename = function() { paste('MNCountyPopChangeData', '.csv', sep='') },
  content = function(file) {
    write.csv(ChangeData, file)
  }) 

output$cityChangeTable <- renderDataTable({
  data <- CityChange
  if (input$County7 != "All"){
    data <- data[data$County %in% input$County7,]
  }
  data
}, options =list(aoColumnDefs = list(list(sClass="alignCenter",aTargets=c(list("_all"))  )),  pageLength=10))  

output$cityChangeChart <- renderChart({
  var <- reactive({input$County8})
  DF <- subset(CityChangeLong, County %in% var())
  names(DF) = gsub("\\.", "", names(DF))
  n4 <- nPlot(PercentChange ~ Year, data = DF, group = "Name", type = 'lineChart')
  n4$addParams(dom = 'cityChangeChart')
  n4$yAxis(axisLabel = "Percent Change from Previous Decade", width = 62)      
  n4$xAxis(axisLabel = "Year")
  n4$xAxis(tickValues=c(1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010))
  #     n3$chart(forceY = c(-100, 100))
  return(n4)
})

output$cityChangeDownload <- downloadHandler(
  filename = function() { paste('MNCityPopChangeData', '.csv', sep='') },
  content = function(file) {
    write.csv(CityChange, file)
  })

output$twpChangeTable <- renderDataTable({
  data <- TwpChange
  if (input$County9 != "All"){
    data <- data[data$County %in% input$County9,]
  }
  data
}, options =list(aoColumnDefs = list(list(sClass="alignCenter",aTargets=c(list("_all"))  )), pageLength=10))  

output$twpChangeChart <- renderChart({
  var <- reactive({input$County10})
  DF <- subset(TwpChangeLong, County %in% var())
  names(DF) = gsub("\\.", "", names(DF))
  n5 <- nPlot(PercentChange ~ Year, data = DF, group = "Name", type = 'lineChart')
  n5$addParams(dom = 'twpChangeChart')
  n5$yAxis(axisLabel = "Percent Change from Previous Decade", width = 62)      
  n5$xAxis(axisLabel = "Year")
  n5$xAxis(tickValues=c(1900, 1910, 1920, 1930, 1940, 1950, 1960, 1970, 1980, 1990, 2000, 2010))
  #     n3$chart(forceY = c(-100, 100))
  return(n5)
})

output$twpChangeDownload <- downloadHandler(
  filename = function() { paste('MNTownshipPopChangeData', '.csv', sep='') },
  content = function(file) {
    write.csv(TwpChange, file)
  })


data(movies, package = "ggplot2")
minx <- min(movies$rating)
maxx <- max(movies$rating)

  output$trendPlot <- renderPlotly({
    # size of the bins depend on the input 'bins'
    size <- (maxx - minx) / input$bins

    # a simple histogram of movie ratings
    p <- plot_ly(movies, x = rating, autobinx = F, type = "histogram",
                 xbins = list(start = minx, end = maxx, size = size))
    # style the xaxis
    layout(p, xaxis = list(title = "Ratings", range = c(minx, maxx), autorange = F,
                           autotick = F, tick0 = minx, dtick = size))
  })

}

There is a lot of unused plots in the ui because I've yet to assemble the dashboard in its entirety, so I apologize for the length of all of this.

I also apologize for any faux pas within this post- I don't use github all that much nor am I computer scientist, so this is a learning experience for me.

Thanks for the help,

Ricky.

Stacked Bar charts with negative and positive series

Hey guys,

I have stumbled upon a chart that should be pretty straightforward, but apparently isn´t. I am attempting to create a bar chart that is stacked, in both positive and negative direction.

Below is a ggplot chart that kind of works.

dat <- read.table(text = "   Division Year OperatingIncome
1  A  2012           11460
                  2  B  2012            7431
                  3  C  2012           -8121
                  4  D  2012           15719
                  5  E  2012             364
                  6  A  2011           12211
                  7  B  2011            6290
                  8  C  2011           -2657
                  9  D  2011           14657
                  10 E  2011            1257
                  11 A  2010           12895
                  12 B  2010            5381
                  13 C  2010           -2408
                  14 D  2010           11849
                  15 E  2010             517",header = TRUE,sep = "",row.names = 1)

dat1 <- subset(dat,OperatingIncome >= 0)
dat2 <- subset(dat,OperatingIncome < 0)
p<-ggplot() + 
  geom_bar(data = dat1, aes(x=Year, y=OperatingIncome, fill=Division),stat = "identity") +
  geom_bar(data = dat2, aes(x=Year, y=OperatingIncome, fill=Division),stat = "identity")

p

The ggplotly routine screws up the layers...

ggplotly(p)

...is there any idea on how to either convert the ggplot chart via ggplotly or even better how to create it from scratch via plot_ly() ??

Thanks a lot in advance.

Cannot download in html from R notebook

The sheer fact of including plotly graphs in the R notebook creates a bug when downloading an .html version of the notebook. The downloaded html file cannot be scrolled. It only displays the very top of the notebook.

I have tried with various functions, including ggplotly.

Setting the spacing between axis label and axis ticks labels

Is there any way to set a spacing between axis labels and axis ticks labels other than changing margins?

Example plot:
plotly::plot_ly(mtcars, x = ~ wt, y = ~ paste0(hp, '0000'))

As in the example plot above the title of the y axis is overlapping tick labels of this axis. Is there a way to set a spacing between them?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.