gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 09:08:06 25 4
gpt4 key购买 nike

我在制作以下图例时遇到问题 ggplot包裹在 ggplotly()只展示一种审美。它目前为每个图例条目显示三个变量( 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()如图所示,图例同一行内的值

here .

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

我在 Windows 10 上使用 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

enter image description here

关于r - 在 plotly R 中包装 ggplot2 时图例中的额外变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com