这个问题在这里已有答案:
我需要在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))
我需要在图表中添加蓝色和红色点的图例 .
谢谢!
2 回答
您无需为每种颜色添加geom . 颜色是一种美学,你连接到一个变量,在你的情况下
index.one
(或.two但它们混淆) .你的例子有点棘手,因为你添加了
geom_line
. 没问题,只需添加审美到geom_point
.另外,因为
index.one
是数字,ggplot2会尝试将它用作连续变量,但它实际上是离散的,因此as.factor
.编辑:我注意到你在1995年没有一点 . 只需用
NA
替换相应年份的index.one
中的值,就不会绘制该点 . 它不会影响该行,因为它从另一个变量中获取值 .这使用
tidyr::gather()
来创建一个长数据集,然后过滤它只绘制值等于1的点的点 .