You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用ggplotly时保留ggplot生成的图例与图形样式?

问题:ggplotly转换后图例与点样式变形,如何保留原ggplot样式并实现交互?

使用plotly包的ggplotly()函数将ggplot生成的图表转为交互式可视化时,图例样式和数据点形状完全改变。需要在保留plotly交互功能的同时,维持原ggplot图表的图例与图形样式。

数据

可直接运行的dput数据:

df <-structure(list(Day = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), Drug = c("A", "B", "B", "C", 
"A", "C", "A", "B", "C", "A", "B", "C", "A", "C", "A", "B", "B", 
"C"), Sex = c("Female", "Male", "Female", "Female", "Male", "Male", 
"Male", "Female", "Male", "Female", "Female", "Male", "Male", "Female", 
"Female", "Male", "Male", "Female"), Y = c(2.192306074, 4.551912798, 
1.574070652, -0.143946163, 5.144422967, 5.724705829, 2.691617258, 
-3.0289955, 0.338102762, -0.558581233, -2.942620032, 1.024670497, 
2.264980803, 2.103722883, 2.091621938, 1.535299922, 1.618399767, 
0.136160703), DrugSex = structure(c(1L, 4L, 3L, 5L, 2L, 6L, 2L, 
3L, 6L, 1L, 3L, 6L, 2L, 5L, 1L, 4L, 4L, 5L), levels = c("A,Female", 
"A,Male", "B,Female", "B,Male", "C,Female", "C,Male"), class = "factor")), row.names = c(NA, 
-18L), class = "data.frame")

原始CSV格式数据:

"","Day","Drug","Sex","Y","DrugSex"
"1",1,"A","Female",2.192306074,"A,Female"
"2",1,"B","Male",4.551912798,"B,Male"
"3",1,"B","Female",1.574070652,"B,Female"
"4",1,"C","Female",-0.143946163,"C,Female"
"5",1,"A","Male",5.144422967,"A,Male"
"6",1,"C","Male",5.724705829,"C,Male"
"7",2,"A","Male",2.691617258,"A,Male"
"8",2,"B","Female",-3.0289955,"B,Female"
"9",2,"C","Male",0.338102762,"C,Male"
"10",2,"A","Female",-0.558581233,"A,Female"
"11",2,"B","Female",-2.942620032,"B,Female"
"12",2,"C","Male",1.024670497,"C,Male"
"13",3,"A","Male",2.264980803,"A,Male"
"14",3,"C","Female",2.103722883,"C,Female"
"15",3,"A","Female",2.091621938,"A,Female"
"16",3,"B","Male",1.535299922,"B,Male"
"17",3,"B","Male",1.618399767,"B,Male"
"18",3,"C","Female",0.136160703,"C,Female"

读取数据的命令:

df <- read.delim("clipboard", sep = ",")

ggplot绘图代码

library(dplyr)
library(ggplot2)

df_means <- df %>% group_by(DrugSex) %>% 
  summarise(color = first(Drug),Mean = mean(Y)) %>% 
  rename(grouping_var = 1) %>% mutate(x = seq(length(unique(grouping_var))))

p <-df %>% ggplot(aes(x = DrugSex, y = Y)) +
  geom_point(aes(color = Drug, shape = DrugSex))+ 
  geom_segment(data = df_means, aes(x=x-0.25, xend=x+0.25, y=Mean, yend=Mean, color= 
  color),inherit.aes = F, show.legend = F)+ 
  theme(legend.position = 'bottom',
        legend.key=element_blank() #transparent legend panel
  )

图表效果对比

  • 原ggplot图表效果:原ggplot图表
  • ggplotly转换后效果:ggplotly转换后图表

内容的提问来源于stack exchange,提问作者Abbas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:55:27