glnvdl glnvdl - 2 years ago 70
R Question

R - ggvis - Ordering axis

I'm playing around with ggvis for the first time. I have trouble ordering my X-axis. ggvis tends to order it alphabetically. I would prefer a different order (analyst, consultant, software engineer, manager, director).

The code/data looks like this:

> str(company$Age)
int [1:19] 35 37 30 28 28 27 25 26 25 25 ...
> str(company$Role)
Factor w/ 5 levels "Analyst","Consultant",..: 3 3 4 4 4 5 2 2 1 1 ...


Ggvis code looks like this:

company %>% ggvis(~Role,~Age) %>%
layer_points()


The result is an alphabetical order.

I found the following post regarding this subject. I can't however figure out how I could apply this directly.

I tried:

company %>% ggvis(~Role,~Age) %>%
layer_points() %>%
add_axis("x", title = "Role", values = c("Analyst","Consultant","Software Engineer","Manager","Director"


But this does not seem to work.

Could you help me determine how I can order this code?

Thank you in advance.

Kind regards

Answer Source

You need to use scale_ordinal to do this:

Sample data as your problem is not reproducible (but it is the same kind of data):

library(ggvis)
library(dplyr)
mydf2 <- iris %>%
  group_by(Species) %>%
  summarize(Sepal.Length = mean(Sepal.Length),
            Sepal.Width = mean(Sepal.Width)) 

Solution:

Initial graph (no ordering here)

mydf2 %>% as.data.frame()  %>% 
  ggvis(x = ~ Species, y = ~ Sepal.Length ) %>%
  layer_bars(fillOpacity := 0.1 )

enter image description here

Custom ordered graph (I am manually changing the order here using the domain argument):

mydf2 %>% as.data.frame()  %>% 
  ggvis(x = ~ Species, y = ~ Sepal.Length ) %>%
  layer_bars(fillOpacity := 0.1 ) %>%
  scale_ordinal('x', domain=c('versicolor','setosa','virginica'))

enter image description here

x-axis needs to be a factor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download