【问题标题】:Reduce space between plotted points in plot() R减少 plot() R 中绘制点之间的空间
【发布时间】:2018-02-08 16:36:30
【问题描述】:

我有一个看似非常简单的问题,但找不到答案。我已经创建了这个图,只是想让两个外部点更靠近中间。

#Sample code
    x=1:3
    y=c(-50,-70,-120)
plot(x,y)

我已经通过设置 par(mar=c(5.1,9,4.1,9)) 尝试了这个reducing the space between plotted points in plot( x, y) type=n,但这只会改变绘图的比例,但不会改变相对距离。我对 qplot 有同样的问题。请注意,我想使用axis() 设置我自己的刻度标签。

【问题讨论】:

  • 显示您用于制作绘图的代码。显示您对par() 的尝试显示您希望如何设置 x 轴标签。尝试制作reproducible example
  • 又快又脏:只需在您的数据集中添加一些虚拟值(这将扩展您的 x 轴)并将这些值的颜色设置为白色(您可以在 plot par 中为 col 提供一个向量)
  • 你的负y轴如何反映你的示例代码y=c(50,70,100)
  • @RuiBarradas 已修复。
  • @AP25,看起来太复杂了,难道没有更合适的方法来选择点之间的间距吗? ggplot 至少应该有一些东西

标签: r plot


【解决方案1】:

您可以在 x 轴点的任一侧添加一些填充。例如,这里有一个函数负责填充并控制轴中断的数量:

x=1:3
y=c(-50,-70,-120)

# Function to plot with padding on either side of x-axis points.
# Padding is set with pad parameter equal to a fraction of the range of the x values.
# The ... argument allows you to pass additional arguments to plot, such as
#  xlab, main, ylim, col, etc.
pad_plot = function(x, y, pad=0.4, n=5, ...) {

  # Get range of x values
  xrng = diff(range(x))

  # Plot, but don't include axis, so that we can directly control the axis labels.
  # Otherwise, plot will add axis breaks at 0, 4, and other values outside the 
  #  range of the data.
  plot(x,y, xlim = range(x) + c(-1,1)*pad*xrng, xaxt="n", ...)

  # Add axis breaks and labels
  axis(side=1, at=pretty(x, n))
}

par(mfrow=c(2,2))
pad_plot(x,y)
pad_plot(x,y, n=2, main="This is a title", pch=16, col="red")
pad_plot(x,y,pad=0.2, n=8)
pad_plot(x,y, pad=2)

【讨论】:

  • 谢谢你的建议。这并不完全令人满意,然后我就拥有了所有这些空白。为什么这个手术这么难?
  • 如果您希望这些点在图中物理上靠得很近,似乎唯一的选择是在具有“典型”纵横比的图中使用大量空白填充(如我的示例所示)或没有填充的非常薄的图。如果我缺少另一个选项,您能否绘制一张您希望情节看起来像的图片并将其图像添加到您的问题中?