添加具有自己的比例和图例的geom

时间:2012-10-19 18:11:07

标签: r ggplot2 legend

这可以说是对这些问题的跟进:

Add legend to ggplot2 line plot

Add vline to existing plot and have it appear in ggplot2 legend?

我希望将一个geom添加到一个具有自己的独立数据,比例和图例元素的图中。

我意识到这可能违反了一些图形原理的语法,但我经常发现自己想要这些元素如垂直或水平线,单点,箭头等会出现在图例中。

当其他几何图形中已经使用了比例时,似乎会增加难度。

使用iris的例子并不是那么漂亮:

p<-qplot(data=iris, x=Petal.Width,
         y=Sepal.Width,
         colour=Species,
         shape=as.factor(round(Petal.Length)),
         linetype=as.factor(round(Sepal.Length)),
         geom=c("line", "point"))

p<-p+geom_vline(xintercept=0.75, aes(linetype="Setosa vs Versicolor"))
p<-p+geom_vline(xintercept=1.75, aes(linetype="Versicolor vs Virginica"))

print(p) 

目前生成的,缺少vline和关联图例的线型。

enter image description here

1 个答案:

答案 0 :(得分:1)

更改geom_vline来电,在xintercept来电中同时包含linetypeaes。现在,linetype没有任何效果(不仅仅是没有出现在图例中)。

qplot(data=iris, x=Petal.Width,
      y=Sepal.Width,
      colour=Species,
      shape=as.factor(round(Petal.Length)),
      linetype=as.factor(round(Sepal.Length)),
      geom=c("line", "point")) +
geom_vline(aes(xintercept=0.75, linetype="Setosa vs Versicolor")) +
geom_vline(aes(xintercept=1.75, linetype="Versicolor vs Virginica"))

## Warning messages:
## 1: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 7. Consider
## specifying shapes manually. if you must have them. 
## 2: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 7. Consider
## specifying shapes manually. if you must have them. 
## 3: Removed 4 rows containing missing values (geom_point). 
## 4: The shape palette can deal with a maximum of 6 discrete values because
## more than 6 becomes difficult to discriminate; you have 7. Consider
## specifying shapes manually. if you must have them. 

enter image description here