r - R plot.default 中的 x Axis 太短

标签 r plot axis

我的 x Axis 太短了。

My Plot

d <- data.frame(x = c(120,200,300), y = rep(1,3))

 plot(d$x, 
      d$y,
      xlim = c(min(d$x), max(d$x)),
      axes = FALSE,
      xlab = "",
      ylab = "")

axis(1, lwd = 2)

显然这并不理想。我知道有许多针对单个绘图实例的解决方案。但是,我以编程方式生成了许多具有不同 x 值的此类图表。因此,我需要一个通用且可直接适用于不同 x 值的解决方案。

下面是一些头脑 Storm 代码:

 #This works but the tick marks are ugly.  I also can't control lwd of axis
 plot(d$x, 
      d$y,
      yaxt="n",
      frame.plot = FALSE,
      xlab = "",
      ylab = "",
      xaxp = c(120, 300, 50)) 

 #this is the solution for this particular case, however, it would not work in general
 plot(d$x, 
      d$y,
      xlim = c(min(d$x)-20, max(d$x)),
      axes = FALSE,
      xlab = "",
      ylab = "")

axis(1, lwd = 2)    

有什么想法吗?

最佳答案

这是一种使用基本 R 图形的方法。逻辑类似于 ggplot2 答案。下面的代码将 x 范围设置为数据范围下方和上方最接近的 50 的倍数,并在每 50 的倍数处放置刻度线。不同地 block 的数据范围。

xfun 计算最小和最大 x 限制。 tick.dist 设置图表中刻度线之间的距离。默认设置为 50。因此,默认情况下,当 which="min" 时,xfun 返回小于 value。当 which="max" 时,xfun 返回大于 value 的 50 的大倍数。

xfun = function(value, which, tick.dist=50) {

  # Calculate minimum x-limit
  if(which=="min") {
    return(value - value %% tick.dist)
  }

  # Calculate maximum x-limit
  if(which=="max") {
    return(value + (tick.dist - value %% tick.dist))
  }
}

现在我们创建四个示例图。

par(mfrow=c(2,2))

# Try out various ranges for the x-values
x_vals = c(-23, 56, 80, 123)

# Set distance between tick marks
tick.dist=50

for (i in 1:length(x_vals)) {
  # Create fake data
  d <- data.frame(x=runif(10, x_vals[i], x_vals[i] + 220), y = rep(3,10))  

  # Set x limits and number of tick marks
  xmin = xfun(min(d$x), "min", tick.dist) 
  xmax = xfun(max(d$x), "max", tick.dist) 
  nticks = as.integer((xmax - xmin)/tick.dist)

  # Plot
  plot(d$x, d$y, xaxt="n", yaxt="n", frame.plot = FALSE,
       xlab = "", ylab = "", xlim=c(xmin, xmax)) 

  # xaxp controls location of min and max x-axis tick marks
  #  as well as the total number of tick marks. 
  #  See ?par("xaxp") for more info.
  axis(1, lwd = 2, xaxp = c(xmin, xmax, nticks))
}

enter image description here

关于r - R plot.default 中的 x Axis 太短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061421/

相关文章:

r - 通过单点登录从 Snowflake 将数据导入 R

r - R中的数字和符号相乘

r - H2O 不能从 H2OParsedData 子集列

python - 获取调整后的 matplotlib 绘图窗口的大小

function - 如何在 Mathematica 中绘制函数和数据?

python - 如何设置子图 Axis 范围

r - 将错误栏添加到具有 reshape 数据的 ggplot

python - 等高线图图例 - Matplotlib

R:以编程方式生成带有上标的绘图 Axis 中断标签

java - Spring WS 客户端 - 如何在不使用 Axis 的情况下为 WSDL 创建映射 POJO