ggvis side-by-side barchart grouped by second variable

强颜欢笑 提交于 2019-12-10 13:58:00

问题


I am in process of migrating from Excel to ggvis for data analysis. For a typical grouped bar chart with two variables, however I have difficulty to plot bar chart side-by-side instead of stacked.

The following data has four steps A, B, C, D with "ratio" data from two features cc, ca. My attempt is to plot the ratio from cc and ca features side-by-side. However, the default plot with stack the two data together. Check the ggvis vignetts has an option to set stack =FALSE. But it would overlap the other feature.

Is there an option in ggvis to do things like "geom_bar(position="dodge")" in ggplot?

library(ggvis)
steps <-c("A","B","C","D","A","B","C","D")
ratio <-c(1.1,1.5,1.7,1.4,1.5,1.7,1.4,1.9)
feature <-c("cc","cc","cc","cc","ca","ca","ca","ca")
shrink <- data.frame(steps,ratio,feature)
shrink %>% ggvis(x= ~steps, y= ~ratio, fill = ~feature) %>% layer_bars()

回答1:


I don't see an easy way to do this yet. But a work around is to explicitly define your x axis as a combination of your x and fill variables:

library(ggivs)
library(dplyr)

steps <-c("A","B","C","D","A","B","C","D")
ratio <-c(1.1,1.5,1.7,1.4,1.5,1.7,1.4,1.9)
feature <-c("cc","cc","cc","cc","ca","ca","ca","ca")
shrink <- data.frame(steps,ratio,feature)


shrink %>% 
   mutate(steps_feature = factor(paste(steps, feature))) %>%
   ggvis(x= ~steps_feature, y= ~ratio, fill = ~feature) %>% 
   layer_bars(stack = FALSE) 

Not entirely satisfactory - you'd want to control the gaps between the bars, and maybe change the labels - but in the right direction. I don't much like these plots anyway, I find them visually confusing, even though they are one of the most common plots around.

I know it's not what you asked, and it takes some users a time to get used to them, but I much prefer a scatter plot with this sort of data:

library(tidyr)
shrink %>%
   spread(feature, ratio) %>%
   ggvis(x = ~ca, y = ~cc, text := ~steps) %>%
   layer_text(fontSize := 35)



来源:https://stackoverflow.com/questions/28553760/ggvis-side-by-side-barchart-grouped-by-second-variable

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