Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggvis - Interactive X axis for bar chart

Tags:

r

shiny

ggvis

I'm looking into building a shiny app with ggvis. For this I'm using a small dataset called "company". It contains employee data where each line represents and employee.

From a ggvis perspective I'm trying the following: Creating a bar chart that shows distribution for the following variables:

  • Age
  • Role
  • Sex

Instead of creating three different bar charts by using the following code:

#Barcharts - Role
company %>% ggvis(~Role,opacity := 0.8, fill:= "firebrick") %>%
  layer_bars() %>%
  scale_ordinal('x', domain=c('Analyst','Consultant','Software Engineer','Manager','Director'))

#Barcharts - Age
company %>% ggvis(~Age,opacity := 0.8, fill:= "firebrick") %>%
  layer_bars()

#Barcharts - Sex
company %>% ggvis(~Sex,opacity := 0.8, fill:= "firebrick") %>%    
  layer_bars()

I'd like to create a ggvis bar chart that allows an input selector.

I've tried the following code:

company %>% ggvis(input_select(c("Sex","Role","Age"), map = as.name)) %>% layer_bars()

The following error is returned:

Error: Visual property x.update is not a variable

The data used would be:

raw <- "Age Sex Role
35   M          Director
37   M          Director
30   M           Manager
28   M           Manager
28   F           Manager
27   M Software_Engineer
25   M        Consultant
26   M        Consultant
25   F           Analyst
25   M           Analyst
25   M           Analyst
25   M           Analyst
25   M           Analyst
25   M           Analyst
25   F           Analyst
25   F           Analyst
25   F           Analyst
24   F           Analyst
25   M           Analyst"


company = read.table(textConnection(raw), header=TRUE)

This makes me believe that ggvis does not allow the x variable to be an input selector item. Is this correct? Is there a solution for this?

Thank you in advance. Kind regards

like image 982
glnvdl Avatar asked Jun 28 '15 16:06

glnvdl


1 Answers

First of all you need to melt your data.frame like this:

library(reshape2)
company <- melt(company, measure.vars=c('Role','Age','Sex'))

And then the following worked for me:

#Barcharts - Age
company %>% ggvis(~value, opacity := 0.8) %>%
  #use filter to pick only the category you want
  filter(variable == eval(input_select(choices=c('Role','Age','Sex')))) %>%
  layer_bars()

I cannot upload the interactive version but the plot looks like this:

enter image description here

And you can pick the category you like

like image 75
LyzandeR Avatar answered Oct 18 '22 17:10

LyzandeR