R图中的阴影区域

时间:2015-04-15 15:19:25

标签: r function plot

我在R中有一个图来分析这个函数的功能行为: -2.5 * log10(x)在不同的地区,输入就像这样

 curve(-2.5*log10(x),0,5,main="Behaviour of magnification function",col=2)
 abline(v=0,col=3)
 abline(v=1,col=4)
 abline(h=0,col=8)

现在我想对v = 1线右侧的那些区域进行着色,并留下两种不同的色调,但是无法弄明白该怎么做。多边形功能不给阴影,请帮忙 谢谢, 阿燕

2 个答案:

答案 0 :(得分:1)

您可以使用panel.first参数在后台绘制。

定义一个绘制函数:

fnShade = function(v,colL,colR) {
  p = par("usr") # limits of the plot 
  rect(p[1],p[3],v,p[4],col=colL,border=NA)
  rect(v,p[3],p[2],p[4],col=colR,border=NA)
  abline(v=v,col=4)
}

然后使用它

curve(-2.5*log10(x),0,5,main="Behaviour of magnification function",col=2,
   panel.first=fnShade(1,5,"grey80"))

如果您愿意,可以将其他abline添加到该功能中。如果需要,应该很容易扩展以绘制4个矩形 - 每个因子一个 - 。

答案 1 :(得分:0)

以下是问题的ggplot解决方案,使用annotate

首先,保存df中的曲线结果:

df <- curve(-2.5*log10(x),0,5,main="Behaviour of magnification function",col=2)

然后使用geom_vline添加垂直线,并使用annotaterect geom添加到阴影区域的数据中。我们使用annotate,因为我们不希望使用this answer中建议的原始数据框中的数据。

plot <- ggplot(data.frame(df)) + 
  geom_line(aes(x, y), size = 1) +
  geom_vline(xintercept  = 1, color = "blue", size = 1) +
  geom_hline(yintercept = 0, color ="grey", size = 1) +
  geom_vline(xintercept = 0, color = "green", size = 1) +
  annotate("rect", xmin = 1, xmax = Inf, ymax = Inf, ymin = -Inf, fill = "blue", alpha = 0.2) + 
  annotate("rect", xmin = -Inf, xmax = 1, ymax = Inf, ymin = -Inf, fill = "green", alpha = 0.2) + 
  labs(title = "Behaviour of magnification function\n") +
  theme_bw()

plot