gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:15:31 27 4
gpt4 key购买 nike

我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com