Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...