![](/img/trans.png)
[英]How to remove the default grey fill for linetype legend in barplot with ggplot2?
[英]How to reproduce the default linetype of ggplot2?
我想在此答案之后将颜色图例与线型图例结合起来。 但是,在指定此处显示的线型时,无法再现默认线型。
这是一个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
产生: 图:默认线型 。
但是,我希望方法A
( df1
和df2
)为实线,方法B
( df3
)为虚线(短划线与上图中的绿线相同)。 在此答案之后,可以通过获得默认线型
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))
产生图:不正确的线型 。 虽然我只有一个所需的图例,但线型显然是不正确的。 但是,即使使用直观的线型
# Initialize the plot with specifying the "intuitive" linetype
g <- g + scale_linetype_manual(name="test",values=c(1,1,2))
我得到一个不正确的结果图:不正确的linetype2 (即,破折号比默认设置更长)。
可能有一种更简单的方法,但使用您已有的,这是一个可能的解决方案。 您注意到,使用linetype = method
可以在图形中为您提供正确的线型,但图例不正确。 我们可以用scale_linetype(guide = "none")
去除第二个图例,但是我们在剩下的图例中有所有实线。 使用guides()
我们可以手动设置线型。 在这种情况下,我查看了您在此处列出的答案,并找到了您想要的行类型的名称。
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.