Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

r - ggvis - Interactive X axis for bar chart

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...