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

Dev*_*i A 5 r legend ggplot2 aesthetics plotly

我无法将下面的传说ggplot包裹在ggplotly()展示只有一个美学.目前,它显示了三个变量(shape,color,linetype每个图例项),但我只想显示一个.

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)
Run Code Online (Sandbox Code Playgroud)

传说只显示linetype,这是期望的结果(见此处).然而,当它包装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)
Run Code Online (Sandbox Code Playgroud)

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

这里.

如何在文件中包装ggplotly或手动编码时覆盖此更改?我在ggplot中添加了一些主题,它们改变了两者中的图例ggplot并且ggplotly很好(例如legend.positionlegend.title)虽然我没有找到任何东西来控制显示的实际变量.

我在Windows 10上使用R版本3.4.0(RStudio版本1.0.143).任何帮助将不胜感激!

Max*_*ers 6

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

gp <- ggplotly(p)
gp[['x']][['data']][[1]][['name']] <- '1'
gp[['x']][['data']][[2]][['name']] <- '2'
gp[['x']][['data']][[3]][['name']] <- '3'
gp
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明