r-我可以在ggplot2中添加一个特定的数据框架列作为图例吗



我想插入一个特定的数据帧列(下面数据帧中的"标签"列(作为ggplot2绘图图例的一部分,考虑到该列没有在绘图中使用。我试着在labs中使用参数tag,但我只得到了列的第一行。

这是绘图代码:

id=c(1,2,3,4)
x=c(0.1,0.2,0.3,0.4)
y1=c(10,20,30,40)
y2=c(300,400,500,640)
labels=c('1-A','2-B','3-C','4-D')
df<-data.table(id=id,x=x,y1=y1,y2=y2,labels=labels)
p<-ggplot(df,aes(x))
(p+geom_point(aes(y=y1, colour='y1'))
+geom_text(aes(y=y1,label=id, colour='y1'),show.legend = F,hjust=0, vjust=0,nudge_x=0)
+geom_point(aes(y=y2/16, colour = 'y2'))
+geom_text(aes(y=y2/16,label=id, colour = 'y2'),show.legend  = F,hjust=0, vjust=0,nudge_x=0)
+scale_y_continuous(sec.axis = sec_axis(~.*16, name = 'y2'))
+labs(tag = df$labels) 
+theme(plot.tag.position = c(0.98, 0.6),legend.title = element_blank()
,legend.justification ='top', plot.margin = unit(c(1,4,1,1),"lines"))
)
df
id   x y1  y2 labels
1:  1 0.1 10 300    1-A
2:  2 0.2 20 400    2-B
3:  3 0.3 30 500    3-C
4:  4 0.4 40 640    4-D

我得到的是这个情节,只有列的第一行";标签";显示数据帧的。

有没有一种方法可以插入整个列";标签";在传说下面?

谢谢!

编辑

我已经用@tacoman-sugestion(fill=labels(和themeguides(fill = guide_legend(override.aes = list(shape=NA)))中的legend.key = element_rect(fill = NA)解决了这个问题。

这是对我有效的代码:

p<-ggplot(df,aes(x))
(p+geom_point(aes(y=y1, colour='y1', fill=labels))
+geom_text(aes(y=y1,label=id, colour='y1'),show.legend = F,hjust=0, vjust=0,nudge_x=0)
+geom_point(aes(y=y2/16, colour = 'y2'))
+geom_text(aes(y=y2/16,label=id, colour = 'y2'),show.legend  = F,hjust=0, vjust=0,nudge_x=0)
+scale_y_continuous(sec.axis = sec_axis(~.*16, name = 'y2'))
+theme(legend.title = element_blank()
,legend.justification ='top', plot.margin = unit(c(1,4,1,1),"lines")
,legend.key = element_rect(fill = NA))
+guides(fill = guide_legend(override.aes = list(shape=NA)))
)

这样?只需添加fill = labels

id=c(1,2,3,4)
x=c(0.1,0.2,0.3,0.4)
y1=c(10,20,30,40)
y2=c(300,400,500,640)
labels=c('1-A','2-B','3-C','4-D')
df<-data.table(id=id,x=x,y1=y1,y2=y2,labels=labels)
p<-ggplot(df,aes(x))
(p+geom_point(aes(y=y1, colour='y1', fill = labels))
+geom_text(aes(y=y1,label=id, colour='y1'),show.legend = F,hjust=0, vjust=0,nudge_x=0)
+geom_point(aes(y=y2/16, colour = 'y2'))
+geom_text(aes(y=y2/16,label=id, colour = 'y2'),show.legend  = F,hjust=0, vjust=0,nudge_x=0)
+scale_y_continuous(sec.axis = sec_axis(~.*16, name = 'y2'))
+theme(plot.tag.position = c(0.98, 0.6),legend.title = element_blank()
,legend.justification ='top', plot.margin = unit(c(1,4,1,1),"lines"))
)

最新更新