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