【问题标题】:Plot functions in R with coordinate axis and arrows在 R 中用坐标轴和箭头绘制函数
【发布时间】:2020-07-07 23:01:28
【问题描述】:

我是R的相对初学者,所以如果这是一个菜鸟问题,请原谅我。

那么,有没有一个包可以提供一个简单的界面来绘制(实数、数学)函数?我需要带箭头的坐标轴(它们的交点应该是 (0;0))和刻度、网格等。我想要与this document 中类似的图。

背景:现在我使用 LaTeX 的 tikzpictureaxis 创建函数图,但几个月以来我一直在使用 R 生成随机检查( R 创建 tex-files 并将它们包含到文档中)如果 R 可以创建类似的图(png,jpg)会很好,因为 axis 非常慢。

谢谢!

【问题讨论】:

  • 目前不知道软件包,但您可以使用 arrowspointsabline 轻松完成此操作。
  • 你能提供一个简单的例子吗? (在正常答案中)

标签: r plot axis-labels


【解决方案1】:

使用arrowspointsabline 等 R 图形工具,您几乎可以绘制任何东西。

示例

op <- par(mar=c(1, 1, 1, 1))  ## adjust outer margins
plot(x, y, type="n", axes=F, asp=1, xlab="", ylab="")  ## asp=1 to maintain 1:1 aspect ratio
lines(x, y, lwd=2)
arrows(par()$usr[1], 0, par()$usr[2], length=.05)  ## par()$usr helps to find xlim and ylim
arrows(0, par()$usr[3], 0, par()$usr[4], length=.05)
points((-5:5)*10, rep(0, 11), pch=3, cex=.6)  ## pch=3 for crosses
points(rep(0, 11), (-5:5)*10, pch=3, cex=.6)
mtext("y", 3, -1, adj=.55, font=8)
mtext("x", 4, -1, padj=-1, las=2, font=8)
abline(h=(-5:5)*10, lty=3, col="gray")
abline(v=(-5:5)*10, lty=3, col="gray")
text(10, -4, "10", font=7, cex=.8)
text(-4, 10, "10", font=7, cex=.8)
par(op)  ## reset par


数据

x <- (-10):10; y <- x^2 - 50

【讨论】:

  • 这也令人印象深刻。我也会调查的。谢谢! (为什么不能接受两个答案?)
【解决方案2】:

为此我为你做了一个小功能

math_plot <- function(f, xlim = c(-2,2), ylim = c(-2,2), 
                      xlab = "x", ylab = "f(x)", ax.ext = .02,
                      frame.plot = F, grid.tick = .1, ...){

  curve(f, from = xlim[1], to = xlim[2], ylim = ylim, 
                      axes = F, xlab = "", ylab = "",
                      frame.plot = frame.plot, ...)

  # x-axis
  axis(1, pos = 0)
  arrows(x0 = xlim[2], x1 = xlim[2] + diff(xlim)*ax.ext, y0 = 0, length = .1)
  mtext(text = xlab, side = 4, line = 0, las = 2, at = 0)

  # y-axis
  axis(2, pos = 0, las = 2)
  arrows(y0 = ylim[2], y1 = ylim[2] + diff(ylim)*ax.ext, x0 = 0, length = .1)
  mtext(text = ylab, side = 3, line = 0, at = 0)

  grid(nx = diff(xlim)/grid.tick, ny = diff(ylim)/grid.tick)
}

# give it a function
math_plot(function(x) 3*x + 2 - 2*x^2, ylim = c(-2,4))

【讨论】:

  • 缺少的功能:箭头 :) 是否可以将标签 x 放置在 x 轴附近(如链接文档中所示) - 以及 y 也可以?
  • @uzsolt 啊,是的。给我一分钟
  • @uzsolt 完成。标签跟随坐标轴,位于位置 0,因此如果 0 不在绘图区域内,它们可能会在绘图区域之外结束。
  • 令人印象深刻,谢谢!当我需要一些东西时,我会理解和修改。谢谢!
猜你喜欢
  • 2012-07-15
  • 2013-01-05
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
相关资源
最近更新 更多