将 ggplot2 图表转换为plotly 时遇到问题。
这是一个可重现的代码:
library(ggplot2)
library(plotly)
# Build the data
dgraf<-data.frame(num=seq(0,2*pi,length.out=100),
name=sample(apply(expand.grid(letters,letters),1,function(x) paste(x,collapse="\n")),100),stringsAsFactors = F)
dgraf$y<-sin(dgraf$num)
rpoint<-sample(25:75,1)
dgraf$ypoint<-NA
dgraf$ypoint[rpoint]<-dgraf$y[rpoint]
dgraf$ymin<-NA
dgraf$ymin[1:rpoint]<-runif(1,0.25,0.75)
dgraf$ymax<-NA
dgraf$ymax[rpoint:100]<-runif(1,-0.75,-0.25)
# ggplot
labels<-c("Data y","Breaking point","Lower line","Higher line")
shapes<-c(21,21,NA,NA)
colors<-c("grey","white","cyan","green")
fills<-c("black","red","black","black")
sizes<-c(3,4,1,1)
linetypes<-c("solid","blank", "solid", "dashed")
dgrafgg<-reshape2::melt(dgraf,id.var="num", measure.var=c("y", "ypoint", "ymin", "ymax"))
gplot<-ggplot(dgrafgg) +
geom_line(aes(x=num,y=value,group=variable, color=variable, linetype=variable),size=1.2) +
geom_point(aes(x=num,y=value,group=variable, color=variable, size=variable, fill=variable, shape=variable), color="white", stroke = 0.1) +
scale_shape_manual(values=shapes, name="Legend", labels=labels) +
scale_color_manual(values=colors, name="Legend", labels=labels) +
scale_fill_manual(values=fills, name="Legend", labels=labels) +
scale_size_manual(values=sizes, name="Legend", labels=labels) +
scale_linetype_manual(values=linetypes, name="Legend", labels=labels) +
scale_x_continuous(breaks = dgraf$num[seq(1,100,by=10)], labels = dgraf$name[seq(1,100,by=10)]) +
labs(title = "Main title", x = "x", y = "y") +
ggthemes::theme_few()
gplot
# Plotly
gplotly <- plotly_build(gplot)
gplotly
关于 ggplot2 图表:
如何从点上完全去除边框(color="white",描边= 0.1)?
关于 plotly 版本:
为什么要修改图例?
为什么要修改x.axis标签?
为什么修改了 geom_lines 并且现在图表中显示了白点?
最佳答案
要在 plotly_bluid(gplot)
之后更改图例标签,您可以使用 ggplo$x$data[[i]]$name
和 ggplo 更改 gplot 信息$x$data[[i]]$legendgroup
。
关于r - plotly_build修改图例和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43278035/