如何重现ggplot2的默认线型?

时间:2019-03-25 11:11:03

标签: r ggplot2

我想将颜色图例与this answer之后的线型图例结合起来。但是,当按here所示指定线型时,将无法复制默认线型。

这是MWE:

# data generation
y1 <- abs(rnorm(10))
y2 <- abs(rnorm(10))
y3 <- abs(rnorm(10))
x <- seq(1,10)
df1 <- data.frame(x,y=abs(y1),type=as.factor("a"),method=as.factor("A"))
df2 <- data.frame(x,y=abs(y2),type=as.factor("b"),method=as.factor("A"))
df3 <- data.frame(x,y=abs(y3),type=as.factor("a"),method=as.factor("B"))

df <- rbind(df1,df2,df3)
inter <- interaction(df$type,df$method)

# ggplot2 colors
hues = seq(15, 375, length = 4)

# Initialize the plot without specifying the linetype
g <- ggplot(df, aes(x,y,colour = inter,linetype = inter)) + 
    geom_line(size=.9) + 
    geom_point(size=1.25) +
    scale_colour_manual(name="test",values=c(hcl(h=hues,l=65,c=100)[1:3]) +
    scale_y_continuous(name="y",trans='log',breaks=c(.1,.2,.5,1)) +
    scale_x_continuous(name="x",labels=as.character(x),breaks=x)

g

产生:FIG: default linetype

但是,我想将方法​​Adf1df2)设为实线,将方法Bdf3)设为虚线(短上图中的绿线为虚线)。在this answer之后,可以通过以下方式获取默认线型

g.plot <- ggplot_build(g)
g.plot$data[[1]]

给予

 colour linetype           y  x PANEL group size alpha
 ...
 10 #F8766D    solid  0.42922736 10     1     1  0.9    NA
 11 #00BA38       22 -2.91845300  1     1     2  0.9    NA
 ...

因此我通过添加来调整图

# Initialize the plot with specifying the linetype
g <- g + scale_linetype_manual(name="test",values=c(1,1,22))

产生FIG: incorrect linetype。虽然我只需要一个图例,但是线型显然不正确。但是,即使使用直观的线型

# Initialize the plot with specifying the "intuitive" linetype
g <- g + scale_linetype_manual(name="test",values=c(1,1,2))

我得到了不正确的结果FIG: incorrect linetype2(即,破折号与默认设置一样长)。

1 个答案:

答案 0 :(得分:0)

可能有一种更简单的方法来执行此操作,但是使用现有的方法,这是一种可能的解决方案。您注意到制作linetype = method可以为图形提供正确的线型,但图例不正确。我们可以使用scale_linetype(guide = "none")摆脱第二个图例,但是剩下的图例中都有所有实线。使用guides(),我们可以手动设置线型。在这种情况下,我查看了您列出的here答案,并找到了所需线型的名称。

g <- ggplot(df, aes(x,y,colour = inter, linetype = method)) + 
  geom_line(size=.9) + 
  geom_point(size=1.25) +
  scale_colour_manual(name="test",values=c(hcl(h=hues,l=65,c=100)[1:3])) +
  scale_y_continuous(name="y",trans='log',breaks=c(.1,.2,.5,1)) +
  scale_x_continuous(name="x",labels=as.character(x),breaks=x) +
  guides(color = guide_legend(title = "inter",
                              override.aes = list(linetype = c("solid", "solid", 22)))) +
  scale_linetype(guide = "none")

enter image description here

相关问题