我想用简单的R绘制两个不同颜色的函数和带有相应图例的点样式.
我有几个问题:
我正在使用pch=21和pch=22.我的理解是它们是"填充"符号.它们确实在图例中按预期填充,但它们在图表上看起来是空心的.怎么了?
我可以在点之间获得更多空间而无需手动指定网格吗?也许通过选择要打印的点数?
随意添加您想要的任何建议.我对R.很新.特别是,有没有更好的方法来绘制两个函数?例如,通过定义函数的向量?并且不会有一种方法可以自动生成图例而无需指定颜色和形状,在普通R?
这是我的代码:
par(new=TRUE)
p1 <- plot(function(x){ x^(2)/2 }
, 0, 100
, xlab = "x"
, ylab = "y"
, ylim = c(0,5000)
, las = 1
, type = "p"
, cex = 0.8
, pch = 21
, col = "red"
)
par(new=TRUE)
p2 <- plot(function(x){ (1-x^(2))/2 }
, 0, 100
, xlab = ""
, ylab = ""
, axes = FALSE
, type = "p"
, cex = 0.8
, pch = 22
, col = "blue"
)
par(new=TRUE)
l <- legend( "topleft"
, inset = c(0,0.4)
, cex = 1.5
, bty = "n"
, legend = c("A", "B")
, text.col = c("red", "blue")
, pt.bg = c("red","blue")
, pch = c(21,22)
)
Run Code Online (Sandbox Code Playgroud)
经过各种探索后,我选择使用par(new=TRUE)"技巧"来叠加这两个函数(而不是使用matplot或绘图和点或布局的组合).这是一个糟糕的举动吗?(编辑:是的,非常糟糕,见下文)+1,如果你不要求我阅读手册;-)

编辑:解决方案摘要
感谢joran和Didzis Elferts,我解决了我的一些问题.为了记录,我想在这里总结一下:
要在图形上获得填充符号,您需要同时指定col(颜色)和bg(背景).即使是pch=21和pch=22,也是如此,它不会自动被指定的颜色填充.要在图例中获取填充符号,您需要同时指定col和pt.bg. 在这里,仅靠bg还不够好.
这是一个非常糟糕的主意,用par(new=TRUE)与axes=FALSE,因为我最初做,因为,重叠的情节不一定使用相同的坐标系.第二个情节的预期功能是(100^2-x^2)/2但是我无意中写了(1-x^2)/2并没有意识到它因为我设置了轴= FALSE.
总而言之,这是我的首选解决方案:
curve( x^2/2
, from = 0
, to = 100
, n = 30
, type = "p"
, pch = 21 # alternatively pch=15 is a solid symbol
, col = "red" # colors the outline of hollow symbol pch=21
, bg = "red" # fills hollow symbol pch=21 with color
, xlab = "x"
, ylab = "y"
)
curve( (100^2-x^2)/2
, from = 0
, to = 100
, n = 30
, type = "p"
, pch = 22 # alternative pch=16
, col = "blue"
, bg = "blue"
, add = TRUE
)
legend( "topleft"
, inset = c(0,0.4),
, cex = 1.5,
, bty = "n",
, legend = c("A", "B"),
, text.col = c("red", "blue"),
, col = c("red", "blue"),
, pt.bg = c("red","blue")
, pch = c(21,22)
)
Run Code Online (Sandbox Code Playgroud)
这产生了一个像joran所示的情节.非常感谢你们两位的帮助.
我想也许你有更好的运气使用curve:
curve(x^(2) / 2,from = 0,to = 100,col = 'red',type = 'p',pch = 16,n = 20)
curve((1-x^(2))/2 + 5000,from = 0,to = 100,col = 'blue',type = 'p',pch = 15,add = TRUE,n = 20)
legend("topleft",
inset = c(0,0.4),
cex = 1.5,
bty = "n",
legend = c("A", "B"),
text.col = c("red", "blue"),
col = c("red", "blue"),
pch = c(16,15))
Run Code Online (Sandbox Code Playgroud)

请注意,我必须略微调整您的功能,以获得与您的图像匹配的输出.
为了避免单独指定颜色和填充(通常是在R中完成事情的方式),我使用了一些较旧的"遗留"符号.curve对于绘制函数或表达式,使用通常要简单得多.它还为您提供了一种更方便的方法来指定要评估的点网格.它还有一个add参数,允许你跳过par你参与的尴尬的黑客攻击.
| 归档时间: |
|
| 查看次数: |
69563 次 |
| 最近记录: |