1

我有这个ggplot

ggplot(dt1, aes(x=x,y=y)) +
    geom_point(color="orange",shape=1, size=1.5) +
    stat_function(fun=function(x) 1.05+.65*sqrt(x)+.1*x, color="blue" ) +
    stat_function(fun=function(x) 1.05-.65*sqrt(x)+.1*x, color="blue" ) +
    stat_smooth(method="lm",formula="y~-1+x",fullrange=TRUE,se = FALSE, color="black")

在此处输入图像描述

数据很简单:

> str(dt1)
'data.frame':   1451 obs. of  2 variables:
 $ y: int  70 161 151 207 100 268 184 156 246 43 ...
 $ x: int  679 1818 1650 2325 992 2412 1830 1398 2207 495 ...

这是一个数据示例:

dt1 <- structure(list(y = c(70L, 161L, 151L, 207L, 100L, 268L, 184L, 156L, 246L, 43L, 125L, 135L, 45L, 93L, 88L, 162L, 131L, 143L, 227L, 177L, 124L, 203L, 243L, 193L, 182L, +
223L, 259L, 215L, 170L, 288L, 67L, 141L, 272L, 160L, 66L, 123L, 226L, 383L, 149L, 354L), x = c(679L, 1818L, 1650L, 2325L, 992L, 2412L, 1830L, 1398L, 2207L, 495L, 1071L, 1200L, 723L, 1162L, 1075L, 1431L, 1169L, 1665L, 2136L, 1402L, 896L, 1951L, 2222L, 1960L, 1601L,+
1787L, 2277L, 1861L, 1432L, 2451L, 626L, 1292L, 2216L, 1499L, 766L, 906L, 2157L, 3419L, 1352L, 3346L)), .Names = c("y", "x"), row.names = c(NA, 40L), class = "data.frame")

我想要一个包含以下 3 个条目的图例:

  • 一个用于显示正确类型点的 geom_point
  • 一个用于显示黑线的 stat_smooth
  • 一个用于 stat_function(即一个图例条目,而不是两个),显示一条蓝线

我怎样才能做到这一点?

4

2 回答 2

3

事实证明,美学是关键。

ggplot(dt1, aes(x=x, y=y)) + 
  geom_point(shape=1,size=1.5, 
             aes(colour="Points",shape='Points', linetype='Points')) +
  stat_function(fun=function(x) 1.05+.65*sqrt(x)+.1*x, 
                aes(colour="Fitted",shape="Fitted",linetype="Fitted")) +
  stat_function(fun=function(x) 1.05-.65*sqrt(x)+.1*x, 
                aes(colour="Fitted",shape="Fitted",linetype="Fitted")) +
  stat_smooth(method="lm",formula="y~-1+x",fullrange=TRUE,se = FALSE, 
              aes(colour="Smoothed",shape="Smoothed",linetype="Smoothed"))+
  scale_colour_manual('',values=c("Points"="orange",
                                  "Smoothed"="black", "Fitted"="blue"))+
  scale_shape_manual('',values=c("Points"=1,"Smoothed"=NA,"Fitted"=NA))+
  scale_linetype_manual('',values=c("Points"=0,"Smoothed"=1,"Fitted"=1))

在此处输入图像描述 也可以看看:

@安德烈在这里

@Earnest A在这里

于 2012-11-03T17:53:49.813 回答
0

这不是最好的方法,但如果是我,我会尝试这样的事情:

par(new=TRUE)
plot(500,360,pch=1,col="orange",size=1.5)
text(500,350,"|")
text(500,340,"|",col="blue")
text(580,360,[text],pos=4)
text(580,350,[text],pos=4)
text(580,340,[text],pos=4)

祝你好运!

于 2012-11-02T22:43:16.187 回答