在 plotly R 中包装 ggplot2 时图例中的额外变量

extra variables in legend when wrapping ggplot2 in plotly R

我无法让 ggplotly() 包裹的以下 ggplot 的图例仅显示一种美学。它目前为每个图例条目显示三个变量(shapecolorlinetype),但我只想显示一个。

此图中只有一个 aes() 值发生变化 (linetype),但其他值对应于特定变量,并且应在我网站上的许多图中保持一致。在我的案例中,简单地从图中删除其他 aes() 值并不是一个可行的解决方案,因为我希望它们在与此类似的其他图中发生变化。此外,隐藏图例并修改 tooltip 以显示信息有效,但不是所需的最终结果。

当运行时,代码如下:

library(ggplot2)
library(plotly)

#aes lists
solute_colors <- c("NO3" = "#BF1616")
source_shapes <- c("rain"= 21)
location_linetypes <- c("1"= 2,"2"= 1,"3"= 3)

#create dataframe
data <- data.frame(
  date = c(1966, 1970, 1972, 1979, 1989, 1990, 1998, 2000),
  concentration = sample(1:8),
  solute = c("NO3", "NO3", "NO3", "NO3", "NO3", "NO3", "NO3", "NO3"),
  location = c("3", "1", "2", "3", "2", "1", "1", "2"),
  source = c("rain", "rain", "rain", "rain", "rain", "rain", "rain", "rain")
)

#ggplot
ggplot(data, aes(x= date, y= concentration, linetype= location, color= solute, shape= source))+
  geom_point() +
  geom_line() +
  scale_shape_manual(values = source_shapes) +
  scale_color_manual(values = solute_colors)+ 
  guides(shape = F, color = F)+ #removes shape and source legends in ggplot, but not in ggplotly
  scale_linetype_manual(values = location_linetypes)

图例仅显示 linetype,这是期望的结果(见 here)。但是,将其包装在 ggplotly

中时
#ggplot p
p<-ggplot(data, aes(x= date, y= concentration, linetype= location, color= solute, shape= source))+
  geom_point() +
  geom_line() +
  scale_shape_manual(values = source_shapes) +
  scale_color_manual(values = solute_colors)+ 
  guides(shape = F, color = F)+ #removes shape and source legends in ggplot, but not in ggplotly
  scale_linetype_manual(values = location_linetypes)
#wrap p in ggplotly
ggplotly(p)

图例显示三个 aes() 值在图例的同一行内

如何在 ggplotly 中包装或在图例中为其手动编码时覆盖此更改?我在 ggplot 中添加了主题,这些主题改变了 ggplotggplotly 中的图例(例如 legend.positionlegend.title),尽管我没有找到任何东西来控制实际显示的变量。

我在 Windows10 上使用 R 版本 3.4.0(RStudio 版本 1.0.143)。非常感谢任何帮助!

不知道如何强制 ggplotly 遵守您的图例标签,但您几乎可以手动覆盖所有内容。

gp <- ggplotly(p)
gp[['x']][['data']][[1]][['name']] <- '1'
gp[['x']][['data']][[2]][['name']] <- '2'
gp[['x']][['data']][[3]][['name']] <- '3'
gp