我正在尝试使用ggplot2
进行绘制,并尝试将标签放置在具有置信区域的平均轨迹上的正确位置。由于无法共享数据,因此创建了一个可复制的示例:
set.seed(456)
library(ggplot2)
library(directlabels)
time<-1:25
df2<-data.frame(time,value=runif(2500),group=as.factor(c(rep('Alpha',1250),rep('Beta',1250))))
ggplot(df2, aes(x=time, y=value,group=group,colour=group))+
stat_summary(geom="ribbon", fun.data=mean_cl_normal,fun.args=list(conf.int=0.95), fill="grey")+
stat_summary(geom="line", fun=mean,size=2,show.legend=TRUE)+
stat_summary(geom="point", fun=mean, color="red",size=3)+
theme(legend.position='none',axis.title=element_text(size=40),
axis.text=element_text(size=30),panel.background = element_blank(),axis.line =
element_line(colour = 'black'))+
geom_dl(aes(label = group),method=list(dl.combine('first.qp','last.qp')),color='black')
如您所见,标签是完全错误的。我正在尝试将标签放在第一个均值点和/或最后一个均值点旁边。根据我的数据,结果更糟:两个标签都在较低的轨迹下并且都重叠。我还得到以下warning
:
┌ Warning: RCall.jl: Warning in regularize.values(x, y, ties, missing(ties)) :
│ collapsing to unique 'x' values
│ Warning in regularize.values(x, y, ties, missing(ties)) :
│ collapsing to unique 'x' values
│ Warning in regularize.values(x, y, ties, missing(ties)) :
│ collapsing to unique 'x' values
│ Warning in regularize.values(x, y, ties, missing(ties)) :
│ collapsing to unique 'x' values
如何解决我的问题并将标签放在每个轨迹的第一个/最后一个平均值旁边?我试图更改method
选项,但没有成功...由于绘制的点是平均值,使用.points
的方法不起作用。而且,如何控制标签的大小?
我尝试了另一个ggplot2
代码:
ggplot(df2, aes(x=time, y=value,group=group,colour=group))+
stat_summary(geom="ribbon", fun.data=mean_cl_normal,
fun.args=list(conf.int=0.95), fill="grey")+
stat_summary(geom="line", fun=mean,size=2,show.legend=TRUE)+
stat_summary(geom="point", fun=mean, color="red",size=3)+
theme(legend.position = 'none',axis.title=element_text(size=40),
axis.text=element_text(size=30),panel.background =
element_blank(),axis.line = element_line(colour =
'black'))+
stat_summary(aes(label=group), fun=mean, geom="text", size=8)
我得到以下图:
如果我只能保留第一个和/或最后一个标签,我认为我已经接近最后一个图了。
答案 0 :(得分:1)
您采用的最后一种方法已经走在正确的轨道上。要使其正常工作,您必须过滤df,使其第一次和最后一次仅包含obs。试试这个:
set.seed(456)
library(ggplot2)
library(dplyr)
time<-1:25
df2<-data.frame(time,value=runif(2500),group=as.factor(c(rep('Alpha',1250),rep('Beta',1250))))
dlabs <- df2 %>%
group_by(group) %>%
arrange(time) %>%
filter(time %in% c(first(time), last(time)))
ggplot(df2, aes(x=time, y=value,group=group,colour=group))+
stat_summary(geom="ribbon", fun.data=mean_cl_normal,fun.args=list(conf.int=0.95), fill="grey")+
stat_summary(geom="line", fun=mean,size=2,show.legend=TRUE)+
stat_summary(geom="point", fun=mean, color="red",size=3)+
theme(legend.position='none',axis.title=element_text(size=40),
axis.text=element_text(size=30),panel.background = element_blank(),axis.line =
element_line(colour = 'black'))+
stat_summary(data = dlabs, aes(label = group, hjust = ifelse(time == first(time), 1.2, -.2)), fun = mean, geom = "text", color = "black") +
scale_x_continuous(expand = expansion(mult = .1))