r - plotly_build修改图例和标签

标签 r plot ggplot2 plotly

将 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

ggplot2 graph

# Plotly

gplotly <- plotly_build(gplot)
gplotly

plotly graph

关于 ggplot2 图表:

如何从点上完全去除边框(color="white",描边= 0.1)?

关于 plotly 版本:

为什么要修改图例?

为什么要修改x.axis标签?

为什么修改了 geom_lines 并且现在图表中显示了白点?

最佳答案

要在 plotly_bluid(gplot) 之后更改图例标签,您可以使用 ggplo$x$data[[i]]$nameggplo 更改 gplot 信息$x$data[[i]]$legendgroup

关于r - plotly_build修改图例和标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43278035/

相关文章:

r - ggplot图例键颜色和透明度

r - 在 r 中循环列的优雅方法

python - 用户警告 : Patch object at has a label of '_K' which cannot be automatically added to the legend

r - 如何提高饼图的可视化质量?

r - 手动颜色和条件填充而不覆盖geom_point中的position_dodge?

r - 有没有一种快速的方法来搜索 R 中的变量?

r - nearPoints 无法从 Shiny 的坐标信息中自动推断出 `xvar`

r - 在一张图表上绘制直方图和密度函数曲线

r - 我可以使用 R ggsurvplot 更改 Kaplan Meier 图中 surv.median.line 的颜色吗?

r - geom_segment 中的 alpha 不起作用