有一些箱形图组:
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))
))
我希望在组之间添加空格(或为每个组添加边框)以显着区分这些组并提高可读性:
有可能这样做吗?例如,在特定刻度之间的X轴上添加自定义空格?
答案 0 :(得分:1)
您可以使用layout
添加shapes
(reference),在您的情况下,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}}