R - ggvis - Ordering axis

放肆的年华 提交于 2019-12-11 09:48:22

问题


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


回答1:


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 )

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'))

x-axis needs to be a factor.




回答2:


You could try reordering outside of ggvis, e.g.,

company[["Role"]] = factor(
                       company[["Role"]]
                     , levels = c("Analyst","Consultant","Software Engineer","Manager","Director")
)



回答3:


How in this example to set the order of the graphs by the Sepal.Length value (from max to min)?

 mydf2 %>% as.data.frame() %>% 
arrange(desc(Sepal.Length)) %>% 
ggvis(x = ~ Species, y = ~Sepal.Length) %>% 
layer_bars()

 mydf2 %>% as.data.frame() %>% 
arrange(desc(Sepal.Length)) %>% 
ggvis(x = ~ Species, y = ~Sepal.Length) %>% 
layer_bars() %>% 
scale_ordinal("x", sort = TRUE)

This code does not give the required result.



来源:https://stackoverflow.com/questions/31082021/r-ggvis-ordering-axis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!