首页 文章

使用geom_point添加图例[重复]

提问于
浏览
1

这个问题在这里已有答案:

我需要在geom_line图中添加一些geom_point的图例 . 例子如下 .

require(dplyr)
require(ggplot2)
set.seed(1111)

我的对象

Sum <- sample(1:50, 10)
year <- c(1990:1999)
index.one <- sample(0:1, 10,replace=TRUE)
index.two <- sample(0:1, 10,replace=TRUE)

df <- data_frame(Sum, year, index.one, index.two)

图表

graph <- ggplot(df, aes(x=year,y=Sum))+ geom_line() +
geom_point(data=df[df$index.one==1,], aes(x=year, y=Sum), colour="red", 
fill="red", shape=22) +
geom_point(data=df[df$index.two==1,], aes(x=year, y=Sum), colour="blue", 
fill="blue", shape=22) +
scale_x_continuous(breaks = seq(1990,1999, by=1))

graph

我需要在图表中添加蓝色和红色点的图例 .

谢谢!

2 回答

  • 0

    您无需为每种颜色添加geom . 颜色是一种美学,你连接到一个变量,在你的情况下 index.one (或.two但它们混淆) .

    你的例子有点棘手,因为你添加了 geom_line . 没问题,只需添加审美到 geom_point .

    ggplot(df, aes(x=year, y=Sum)) +
      geom_point(aes(colour=as.factor(index.one))) + geom_line() +
      scale_colour_manual(values=c(`1`='blue', `0`='red'))
    

    另外,因为 index.one 是数字,ggplot2会尝试将它用作连续变量,但它实际上是离散的,因此 as.factor .

    enter image description here

    编辑:我注意到你在1995年没有一点 . 只需用 NA 替换相应年份的 index.one 中的值,就不会绘制该点 . 它不会影响该行,因为它从另一个变量中获取值 .

  • 1

    这使用 tidyr::gather() 来创建一个长数据集,然后过滤它只绘制值等于1的点的点 .

    library(tidyr)
    df1 <- gather(df, index, value, 3:4)
    ggplot(df1, aes(x = year, y = Sum)) + 
      geom_line() + 
      geom_point(data = df1 %>% filter(value == 1), 
                 aes(colour = index, fill = index), shape = 22) + 
      scale_x_continuous(breaks = seq(1990,1999, by=1)) + 
      scale_fill_manual(values = c("red", "blue")) + 
      scale_colour_manual(values = c("red", "blue"))
    

相关问题