首页 > 解决方案 > 在 ggplot2 中使用线型和颜色示例作为轴标签

问题描述

我有一个四线图,有两种不同的线型(实线和虚线)和两种颜色。我想在图表下方显示一个表格,其中包含有关每条曲线的一些信息,例如:

前任

该表y轴的标签为“S.2”、“D.2”、...

是否可以使用作为曲线外观示例的标签(对于 y 轴)而不是文本?比如图例中的?

那是不是“S.2”有一条短的蓝色虚线?

这是生成情节的代码

require(ggplot2)
require(grid)
require(gtable)

## graph
g1<-ggplot() + aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="1",linetype="S") + geom_line()+
    geom_line(aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="1",linetype="D"))+
    geom_line(aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="2",linetype="S"))+
    geom_line(aes(x=seq(0,5,.1),y=cumsum(sample(0:10,51,replace = T)),colour="2",linetype="D"))+
   scale_colour_manual(breaks=c("1","2"),values=c("#cd7118","#1874cd"))+
   scale_x_continuous(limits = c(0,5),breaks = 0:5,expand=c(0,0))+
   scale_linetype_manual(breaks=c("S","D"),values=c("solid","dashed"))+
   theme(
    axis.line = element_line(size = 0.2, linetype = 'solid',colour = "black"),
    axis.text = element_text(size=10),
    axis.title = element_blank(),
    legend.title = element_blank(),
    legend.background = element_blank(),
    legend.key = element_blank(),
    legend.position = c(.1,.5)
  )

## table
count<-data.frame(time=rep(0:5,4),count=rep(0:5,4),col=c(rep("1",12),rep("2",12)),lintype=rep(c(rep("S",6),rep("D",6)),2))
g2<-ggplot(count, aes(x = time , y = interaction(factor(lintype),factor(col)), colour=factor(col), label=count)) +
  geom_text(size=4) +
  scale_colour_manual(breaks=c("1","2"),values=c("#cd7118","#1874cd"))+
  scale_x_continuous(limits = c(0,5),breaks = 0:5,expand=c(0,0))+
  theme(
    legend.position = "none",
    panel.background = element_rect(fill = "white",colour = "white",size = 0.5, linetype = "solid"),
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    axis.line = element_blank(),
    axis.text.x = element_blank(),
    axis.text.y = element_text(size=10, color = 'black',margin =  margin(t = 0, r = 20, b = 0, l = 0)),
    axis.ticks=element_blank(),
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    plot.title = element_text(size=10),
    plot.margin = margin(t=1,b=1,r=15,l=10,unit="pt")
 )
#
merge = rbind(ggplotGrob(g1), ggplotGrob(g2), size="last")
panels <- merge$layout$t[grep("panel", merge$layout$name)]
merge$heights[panels[1]] <- unit(10,"cm")
merge$heights[panels[2]]<-unit(6,"lines")
merge <- gtable_add_rows(merge, heights = unit(1,"line"), 1)
merge$layout$clip[merge$layout$name=="panel"]<-"off"

grid.draw(merge)

标签: rggplot2

解决方案


推荐阅读