RCharts lineChart Features - r

I am trying to embed an RChart into a shiny app. Specifically, working with the function nPlot and the type=lineChart NVD3 feature. I am trying to plot 3 density curves for simulated Normal data. I am trying to achieve some of the functionality described in the example below:
http://nvd3.org/ghpages/line.html
My issues:
How to have different colours for different density curves?
How to have the feature to click on group variable (1), (2), (3) to effectively remove the selected density. Similar to clicking on "Sine Wave" (top right) in the example to remove the orange sine curve?
How to add x-axis and y-axis labels? My $params$xAxis= call does not work.
Below are my server.R and ui.R files:
## server.r
library(rCharts)
library(shiny)
x <-rnorm(1000,0,1)
y <-rnorm(1000,1,1)
z <-rnorm(1000,2,1)
out <- c(x,y,z)
grp <- c(rep(0,1000),rep(1,1000),rep(2,1000))
data <- as.data.frame(cbind(out,grp))
dens <- by(data$out, data$grp, density)
d <- unlist(c(dens[[1]][1][1], dens[[2]][1][1], dens[[3]][1][1]))
support <- unlist(c(dens[[1]][2][1], dens[[2]][2][1], dens[[3]][2][1]))
grpvar <- c(rep(0,length(unlist(dens[[1]][1][1]))), rep(1,length(unlist(dens[[2]][1][1]))), rep(2,length(unlist(dens[[3]][1][1]))))
dat <- as.data.frame(cbind(d,support,grpvar))
shinyServer(function(input, output) {
output$myChart <- renderChart({
p1 <- nPlot(support~d, group=grpvar, data = dat, type = "lineChart")
p1$addParams(dom = 'myChart')
p1$params$width = 600
p1$params$height = 400
p1$params$xAxis = "Support"
p1$params$yAxis = "Density"
p1$chart(tooltipContent = "#! function(key, x, y, e){
return '<b>Group</b>: ' + e.point.grpvar
} !#")
return(p1)
})
})
## ui.R
library(rCharts)
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("rCharts: Interactive Charts from R using NVD3.js"),
sidebarPanel(
wellPanel(
helpText( "Look at the pretty graph"
)
),
wellPanel(
helpText( "Look at the pretty graph"
)
),
wellPanel(
helpText( "Look at the pretty graph"
)
)
),
mainPanel(
div(class='wrapper',
tags$style(".Nvd3{ height: 600px;}"),
showOutput("myChart","Nvd3")
)
)
))
Thanks in advance for any help/advice you can provide.

You will just need to add quotes around grpvar, so
p1 <- nPlot(support~d, group="grpvar", data = dat, type = "lineChart")

Related

doing map using shiny and ggplot2

I am unable to subset a dataframe within a reactive shiny structure and display it as plot (using ggplot).
I want to have something with map like that, in my shiny app and of course to change the map with the "Choisir une votation"(refering to my input$objet)
here is my ui.r
library(shiny)
shinyUI(fluidPage(
titlePanel("Swiss votations tool"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("objet", "Choisir une votation",
levels((df.merge$Date.et.objet))
)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("plot")
)
)
))
and my server.r (i think i'm doing something with the reactive wrong and/or stupid here...)
shinyServer(function(input, output) {
df.merge2<-reactive({
df.merge2<-df.merge[input$objet,]
d <- as.data.frame(df.merge2)
d
})
output$plot <- renderPlot({
df.merge2<-df.merge2()
p <- ggplot() +geom_polygon(data=df.merge2,
aes(fill =as.numeric(df.merge2$Pourcentage.de.oui),
x = df.merge2$long, y = df.merge2$lat, group = df.merge2$group))
p <- p+geom_path(data=df.merge2,
aes(fill=as.numeric(df.merge2$Pourcentage.de.oui),x =
df.merge2$long, y = df.merge2$lat, group = df.merge2$group),
color = "white", size = 0.1)
p <- p+scale_fill_gradient(low ="#ffffcc" , high = "#253494")
print(p)
})
})
Think you for help, I quite new to shiny
my data:
dataframe with
str(df.merge)
'data.frame': 156672 obs. of 26 variables:
and geographic informations

Shiny slider input filter not working for ggplot but works for dataset

I am new to shiny and have a problem about the slider input, it works well for the dataset but not working for my histogram, could you please help me to look at it, thanks.
Overview
I am trying to build a shiny application to display the attitude{datasets}, the first tab just displays the data, the slider works pretty well, but in the second tab the slider input not works for my histogram. I don't know why, I tried rChart before it also works. Please ignore the about.md file, it's just description.
Code
ui.r
library(shiny)
require(markdown)
library(ggplot2)
# Define UI for application that draws a histogram
shinyUI(
navbarPage("Employee attitude survey",
# multi-page user-interface that includes a navigation bar.
tabPanel("Explore the Data",
sidebarPanel(
sliderInput("rating",
"Employee rating filter:",
min = 1,
max = 100,
value = c(10,50))
),
# Show a plot of the generated distribution
# mytable1: dataset
# distPlot: histogram
mainPanel(
tabsetPanel(
tabPanel(p(icon("table"), "Dataset"),
dataTableOutput("mytable1")),
tabPanel(p(icon("search"), "Visualize the Data"),
plotOutput("distPlot"))
)
)
),
tabPanel("About",
mainPanel(
includeMarkdown("about.md")
)
) # end of "About" tab panel
)
)
server.R
library(shiny)
library(ggplot2)
# Define server logic required to draw a histogram and a table
shinyServer(function(input, output) {
# table to display the attitude, slider works
output$mytable1 = renderDataTable({
attitude[which(attitude$rating <= input$rating[2] & attitude$rating >= input$rating[1]), ]
})
# histogram of rating, but slider not works
output$distPlot <- renderPlot({
df <- attitude[which(attitude$rating <= input$rating[2] & attitude$rating >= input$rating[1]), ]
p1 <- ggplot() + aes(df[,"rating"])
p1 <- p1 + geom_histogram(binwidth=2, col="skyblue", aes(fill=..count..), alpha=0.6)
p1
})
})
My Question
Why the slider not working for my ggplot histogram. But works for the dataset ?Thanks a lot.
Try this
# histogram of rating, but slider not works
output$distPlot <- renderPlot({
df <- attitude[which(attitude$rating <= input$rating[2] & attitude$rating >= input$rating[1]), ]
test <<- (df[,"rating"])
p1 <- ggplot() + aes(test)
p1 <- p1 + geom_histogram(binwidth=2, col="skyblue", aes(fill=..count..), alpha=0.6)
p1
})

R, Shiny, plotting a reactive data frame (data goes "missing")

Given the following ui.R and server.R and circuit.csv; I can produce a simple plot which reacts to the user input (power in this case).
However, not all values for power are returned. For example, .5 produces a plot whereas .6 does not, so on and so forth at random occurrence throughout the power range.
If i plot as a table instead, to check my work, same thing, certain power inputs work as expected and others produce no table, and also no plot when asking to plot.
ui.R
library(shiny)
library(ggplot2)
shinyUI(fluidPage(
hr(),
sidebarLayout(
sidebarPanel(
sliderInput("power",label = "Power",
min = 0, max = 5, value = .5, step = .1)
),
mainPanel(
p("Lum vs Distance by Power"),
plotOutput('plot1')
)
)
))
server.R
library(shiny)
library(ggplot2)
df <- read.table(file = "circuit.csv", sep=",", header = TRUE)
shinyServer(function(input, output) {
output$plot1 <- renderPlot({
df2 <- subset(df,df$pow==input$power)
p <- ggplot(df2)+
geom_point(aes(x=dist, y=lum))
print(p)
})
})
Link to github (for csv data)
I would post images but am not allowed to do so at this time.

Rcharts nPlot() Percentages with discrete/multiBarChart

I want to use the nPlot() function in RCharts to plot percentages of people falling into discrete groups, rather than frequencies.
For example: Using the HairEyeColor data/code below I am able to consider the percentage of people with different hair colors (my grouping variable), as a function of their eye color.
## server.r
library(rCharts)
library(shiny)
library(reshape)
HairEyeColor1 <- melt(round(prop.table(HairEyeColor[,,1],2)*100,2))
names(HairEyeColor1) <- c("Hair", "Eye", "Percent")
shinyServer(function(input, output) {
output$myChart <- renderChart({
p1 <- nPlot(Percent ~ Eye, group = "Hair", data = HairEyeColor1, type = multiBarChart")
p1$addParams(dom = 'myChart')
return(p1)
})
})
## ui.R
library(rCharts)
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("rCharts: Interactive Charts from R using NVD3.js"),
sidebarPanel(
wellPanel(
helpText( "Look at the pretty graph"
)
),
wellPanel(
helpText( "Look at the pretty graph"
)
),
wellPanel(
helpText( "Look at the pretty graph"
)
)
),
mainPanel(
div(class='wrapper',
tags$style(".Nvd3{ height: 400px;}"),
showOutput("myChart","Nvd3")
)
)
))
Say I just wanted to look at a single factor, like Hair. Is there a way to plot their percentages using nPlot()?
prop.table(rowSums(HairEyeColor[,,1]))
Black Brown Red Blond
0.2007168 0.5125448 0.1218638 0.1648746
With type=multiBarChart I have tried:
p1 <- nPlot(Percent ~ , group = "Hair", data = HairEyeColor1, type = multiBarChart")
This fails entirely. I have also tried:
p1 <- nPlot(Percent ~ 1, group = "Hair", data = HairEyeColor1, type = multiBarChart")
This at least passes some graph to Shiny UI. But this looks hideous and functionality (appearance of X/Y-axis, clicking on graph) is all lost.
I thought this would be appropriate for nPlot(type=discreteBarChart) but the data layout for this seems to want a dataframe with a single factor variable. So I can't quite see how to trick nPlot(type=discreteBarChart) into taking a vector of proportions/percentages.
Any suggestions appreciated.
Here is how to do it with nPlot. You can see the resulting plot here. If you want to stack the bars by default, add the line n1$chart(stacked = TRUE) before you print the chart.
# prepare data
require(plyr)
dat = as.data.frame(HairEyeColor)
dat = ddply(dat, .(Hair), summarize, Freq = sum(Freq), Group = "A")
# draw chart
require(rCharts)
n1 <- nPlot(Freq ~ Group, data = dat, group = 'Hair', type = 'multiBarChart')
n1

RCharts scatterChart Enhanced Features

I'm trying to embed an RChart into a shiny app. I'm specifically using the nPlot function to create a type=scatterChart NVD3 style plot. In the NVD3 website example below, there are two pieces of functionality I am interested in getting to work in my RCharts shiny app:
http://nvd3.org/ghpages/scatter.html
It appears that a "rug" is included along the x-axis and y-axis of the above example, demonstrating marginally where the x and y points occur most frequently along their respective supports.
Further, when one clicks on the chart and hovers over a specific point a vertical and horizontal line appear noting the (x,y) location of the corresponding point.
Does anyone know how to expand my code below to achieve these two pieces of functionality. Shiny server.r and ui.r scripts are included below.
## server.r
library(rCharts)
library(shiny)
x <- rnorm(100)
y <- rnorm(100)
dat <- as.data.frame(cbind(x,y))
shinyServer(function(input, output) {
output$myChart <- renderChart({
p1 <- nPlot(y ~ x, data = dat, type = "scatterChart")
p1$addParams(dom = 'myChart')
p1$params$height=400
p1$params$width=650
return(p1)
})
})
## ui.R
library(rCharts)
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("rCharts: Interactive Charts from R using NVD3.js"),
sidebarPanel(
wellPanel(
helpText( "Look at the pretty graph"
)
),
wellPanel(
helpText( "Look at the pretty graph"
)
),
wellPanel(
helpText( "Look at the pretty graph"
)
)
),
mainPanel(
div(class='wrapper',
tags$style(".Nvd3{ height: 400px;}"),
showOutput("myChart","Nvd3")
)
)
))
Thanks in advance for any advice you can provide.
This can be achieved using the following code:
p1$chart(
showDistX = TRUE,
showDistY = TRUE
)
return(p1)
Also, just as a note, while direct manipulation of p1$params works, it might be safer to specify height and width in this way:
p1 <- nPlot(
y ~ x,
data = dat,
type = "scatterChart",
height = 400,
width = 650
)

Resources