首页 > 解决方案 > 在 ggplot2 图表上使用 ggplotly 不适用于箱线图可变宽度或异常值形状变化

问题描述

当我在 ggplot2 图形上使用 ggplotly 时,会重置 ggplot2 的某些功能。

代码示例:

library(tidyverse)
db <- iris

# Changing the N in one of the categories for the example:
db$Sepal.Length[1:40] <- NA

p <- db %>% ggplot(aes(Species, Sepal.Length)) +
geom_boxplot(varwidth = TRUE, outlier.shape = NA)

p

图片1

使用ggplotly(p)时,varwidth 选项不起作用,并且圆形的异常形状返回。这是 ggplolty 的内在品质吗?如果是这样,我如何在 ggplotl2 中获得这些选项?

图二

谢谢!

标签: rggplot2plotlyboxplot

解决方案


Plotly 似乎确实没有继承所有 ggplot 参数。至少可以在此线程之后更改异常值: https ://github.com/ropensci/plotly/issues/1114

library(tidyverse)
library(plotly)
p <- iris %>% ggplot(aes(Species, Sepal.Length)) +
  geom_boxplot() 

# Need to modify the plotly object and make outlier points have opacity equal to 0
p <- plotly_build(p)

for(i in 1:length(p$x$data)) {
  p$x$data[[i]]$marker$opacity = 0
}

p

异常值被移除。我不确定是否可以包含var.width在情节箱图中。

我不确定是否var.width真的有助于可视化- 包括我自己在内的许多人在比较条形宽度方面并不是很好......为了比较样本量,实际显示值可能更清楚,例如geom_jitter

p <- db %>% ggplot(aes(Species, Sepal.Length)) +
  geom_boxplot() +
  geom_jitter(width = 0.2)

ggplotly(p)

在此处输入图像描述


推荐阅读