ggplot2:图中没有点时图例中的点和线

时间:2018-02-10 22:49:18

标签: r ggplot2

enter image description here是否可以在图例上同时显示图表和线条而图中没有任何点?

例如,我有:

df1 <- data.frame(
    sex = factor(c("Female","Female","Male","Male")),
    time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
    total_bill = c(13.53, 16.81, 16.24, 17.42)
)

library(ggplot2)
lp1 <- ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex, colour=sex)) + geom_line() + geom_point(size = 2.5)
lp1

lp1 + scale_colour_discrete(name  ="Payer",
                        breaks=c("Female", "Male"),
                        labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

我想从我的情节中删除这些点,但请将其保留在图例中。我怎么做?我尝试将geom_point的大小设置为零,并将颜色设置为NULL,但它会消除图例中的点。提前感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

您可以在alpha = 0中设置geom_point,然后覆盖此值,将guides(colour = guide_legend(override.aes = list(alpha = 1)))添加到您的地图中。

lp1 <- ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex, colour=sex)) + 
        geom_line() + 
        geom_point(size = 2.5, alpha = 0)
lp1 + guides(colour = guide_legend(override.aes = list(alpha = 1)))

enter image description here