我希望使用ggplot创建散点图来展示方法比较数据。该图应该包含原始数据、理想线和带误差的拟合线。图例应该显示理想线和拟合线的线型/线宽/线颜色。
我可以得到大部分我想要的内容,但是有以下问题需要解决:
- 图例显示每种线型都有2条线,为什么?如何解决? - 我更喜欢图例矩形没有粉色背景(如果我不指定填充颜色,则矩形背景变为默认灰色,这也不太好看)
样例代码:
我可以得到大部分我想要的内容,但是有以下问题需要解决:
- 图例显示每种线型都有2条线,为什么?如何解决? - 我更喜欢图例矩形没有粉色背景(如果我不指定填充颜色,则矩形背景变为默认灰色,这也不太好看)
样例代码:
set.seed(603)
x.raw=rnorm(n=30, mean=50, sd=20)
y.raw=x.raw+rnorm(n=30, mean=2, sd=2)
x.raw=round(x.raw, 2); y.raw=round(y.raw, 2)
df=data.frame(x=x.raw, y=y.raw)
require(ggplot2, quietly=TRUE)
theme_set(theme_bw())
xy.range=range(df$x, df$y)
p=ggplot(df, aes(x=x, y=y)) +
geom_point(shape=ifelse(nrow(df)>49, 1, 16)) +
geom_smooth(method=lm, fill="red1", aes(colour="Fitted", linetype="Fitted")) +
geom_abline(intercept=0, slope=1, aes(colour="Ideal", linetype="Ideal")) +
scale_colour_manual(name="Lines", values=c("Ideal"="blue", "Fitted"="red")) +
scale_linetype_manual(name="Lines",
values=c("Ideal"="solid", "Fitted"="twodash")) +
scale_x_continuous(name="Control", limits=xy.range) +
scale_y_continuous(name="Evaluation", limits=xy.range) +
opts(title="Method Comparison")
p
非常感谢大家抽出时间回复。虽然有一定的逻辑可循,但试错方法并不是我所能得到的。我稍微修改了代码:
- 将geom_point放在最后,这样点就不会被覆盖
- 保持连续调用规模,以便强制x和y轴限制相同
- 类似的备注,添加aspect.ratio=1,现在理想的线条呈45°角延伸至角落,效果与Cleveland相近
最终代码:
ggplot(df, aes(x=x, y=y)) +
geom_smooth(method=lm, se=FALSE, size=1, aes(colour="Fitted", linetype="Fitted")) +
geom_smooth(method=lm, fill="red", colour="red", linetype="twodash", size=1) +
geom_line(data = data.frame(x=0, y=0), aes(colour = "Ideal", linetype = "Ideal"), size=1) +
#geom_abline(intercept=0, slope=1, aes(colour = "Ideal", linetype = "Ideal"), size=0) +
geom_abline(intercept=0, slope=1, colour = "blue", linetype = "solid", size=1) +
geom_point(shape=ifelse(nrow(df)>49, 1, 16)) +
scale_colour_manual(name="Lines", values=c("Ideal"="blue", "Fitted"="red")) +
scale_linetype_manual(name="Lines", values=c("Ideal"="solid", "Fitted"="twodash")) +
scale_x_continuous(name="Control", limits=xy.range) +
scale_y_continuous(name="Evaluation", limits=xy.range) +
opts(title="Method Comparison", aspect.ratio=1) +
theme_bw()