R在图表箱图中添加分隔线

时间:2017-11-21 10:32:29

标签: r plotly boxplot

有一些箱形图组:

dat <- data.frame(xval = sample(100,1000,replace = TRUE),
                  group_af = as.factor(sample(c("a","b","c", "e", "f"),1000,replace = TRUE)),
                  group_xyz = as.factor(sample(c("x","y","z"),1000,replace = TRUE)))
dat <- dat %>% 
  mutate(aux_var = as.factor(paste0(group_af, "-", group_xyz))) 
lvls <- levels(dat$aux_var)

dat %>%
  plot_ly() %>% 
  add_trace(x = ~as.numeric(aux_var), 
            y = ~xval, 
            color = ~group_xyz, 
            type = "box",
            hoverinfo = "none",
            boxpoints = FALSE) %>%
  layout(boxmode = "group") %>%
  add_markers(x = ~jitter(as.numeric(aux_var)), 
              y = ~xval, 
              color = ~group_xyz,
              marker = list(size = 3),
              hoverinfo = "text",
              text = ~paste0("Group: ", aux_var, "<br>xval: ", xval),
              showlegend = TRUE) %>%
  layout(
    xaxis = list(tickmode = "array", 
                 tickvals = c(1:length(lvls)),
                 # ticktext = lvls
                 ticktext = sapply(lvls, function(x) gsub("-.*$", "", x))
                 ))

enter image description here

我希望在组之间添加空格(或为每个组添加边框)以显着区分这些组并提高可读性:

enter image description here

有可能这样做吗?例如,在特定刻度之间的X轴上添加自定义空格?

1 个答案:

答案 0 :(得分:1)

您可以使用layout添加shapesreference),在您的情况下,lines多个library(plotly) dat <- data.frame(xval = sample(100,1000,replace = TRUE), group_af = as.factor(sample(c("a","b","c", "e", "f"),1000,replace = TRUE)), group_xyz = as.factor(sample(c("x","y","z"),1000,replace = TRUE))) dat <- dat %>% mutate(aux_var = as.factor(paste0(group_af, "-", group_xyz))) lvls <- levels(dat$aux_var) upd <- dat %>% plot_ly() %>% add_trace(x = ~as.numeric(aux_var), y = ~xval, color = ~group_xyz, type = "box", hoverinfo = "none", boxpoints = FALSE) %>% layout(boxmode = "group") %>% add_markers(x = ~jitter(as.numeric(aux_var)), y = ~xval, color = ~group_xyz, marker = list(size = 3), hoverinfo = "text", text = ~paste0("Group: ", aux_var, "<br>xval: ", xval), showlegend = TRUE) %>% layout( xaxis = list(tickmode = "array", tickvals = c(1:length(lvls)), # ticktext = lvls ticktext = sapply(lvls, function(x) gsub("-.*$", "", x)) )) upd %>% layout(shapes = list(c(type='line', x0= 3.5, x1= 3.5, y0=0, y1=100, line=list(width=1)), c(type='line', x0= 6.5, x1= 6.5, y0=0, y1=100, line=list(width=1)), c(type='line', x0= 9.5, x1= 9.5, y0=0, y1=100, line=list(width=1))))

{{1}}

enter image description here