让抖动出现在 ggplotly 中

Getting jitter to show up in ggplotly

我正在尝试绘制一个带有因子轴的散点图,为值添加抖动以提高可读性。

我能够在 ggplot2 中获得想要的效果,但是当我尝试用 plotly 包装它时,抖动并没有成功。有什么方法可以让它发挥作用吗?

一个正在发生的事情的例子。下面的 g 看起来是正确的,但是 p 然后失去了抖动。

data<-data.frame(cbind(
  sample(c('level 1', 'level 2', 'level 3'), 100, replace = TRUE),
  sample(c('level 1', 'level 2', 'level 3', 'level 4'), 100, replace = TRUE)))

names(data)<-c('factor1', 'factor2')

g <- ggplot(data, aes(x=factor1, y=factor2)) 
g <- g + geom_point(position = position_jitter(w = 0.2,h = 0.2))
#g <- g + geom_jitter(width = .2, height = .2)
g <- g +xlab('Category One')
g <- g +ylab('Category Two')

g

p <- ggplotly(g)
p

也许有解决办法。用整数替换你的因子,然后重新标记。

data<-data.frame(cbind(
    sample(1:3, 100, replace = TRUE),
    sample(1:4, 100, replace = TRUE)))

names(data)<-c('factor1', 'factor2')

g <- ggplot(data, aes(x=factor1, y=factor2)) 
g <- g + geom_point(position = position_jitter(w = 0.2,h = 0.2)) + scale_x_continuous("Factor 1", breaks = c(1,2,3)) + scale_y_continuous("Factor 2", breaks = c(1,2,3,4))
ggplotly(g)

重新标记 x 和 y 刻度

x <- list(
  tickprefix = "Level"
)

y <- list(
  tickprefix = "Level"
)

g %>% layout(xaxis = x, yaxis = y)

这个有效:

data<-data.frame(cbind(
  sample(1:3, 100, replace = TRUE),
  sample(1:4, 100, replace = TRUE)))

names(data)<-c('factor1', 'factor2')

g <- ggplot(data, aes(x=factor1, y=factor2)) 
g <- g + geom_point(position = position_jitter(w = 0.2,h = 0.2)) + scale_x_continuous("Factor 1", breaks = c(1,2,3)) + scale_y_continuous("Factor 2", breaks = c(1,2,3,4))
p <- ggplotly(g)

x <- list(title = "Category One",tickmode = "array",tickvals = c(1,2,3) , ticktext = c("A", "B", "C"))
y <- list(title = "Category Two",tickmode = "array",tickvals = c(1,2,3,4) , ticktext = c("A", "B", "C", "D"))

p <- p %>% layout(xaxis = x, yaxis = y)
p