【问题标题】:ggplot2 doesn't plot all the pointsggplot2 没有绘制所有点
【发布时间】:2022-01-05 17:28:55
【问题描述】:

我试图在 ggplot2 中绘制一个圆形的 7 个点的图形,但尝试绘制它们只显示 6 个,我不知道为什么会发生这种情况。

代码如下:

# Function for the points
circleFun <- function(center = c(-1, 1), diameter = 1, npoints = 7) {
  r <- diameter / 2
  tt <- seq(0, 2 * pi, length.out = npoints)
  xx <- center[1] + r * cos(tt)
  yy <- center[2] + r * sin(tt)
  return(data.frame(x = xx, y = yy))
}

# example with 7 points
ej <- 
  circleFun(diameter = 50, center = c(50,50), npoints = 7)


# plot

ej |> 
  ggplot(aes(x = x, y = y)) +
  geom_point(alpha = 0.4) +
  theme_bw()

有人知道为什么会这样吗?

【问题讨论】:

  • 第 1 行和第 7 行是相同的,所以它们的点是重叠的。这个点有点暗(根据你的alpha = 0.4)。您可以通过添加x = jitter(x) 来使这一点变得明显(为了演示,您不会在生产中这样做)。鉴于相同的数据,我不确定您希望看到什么。

标签: r ggplot2


【解决方案1】:

第 1 行和第 7 行相同,因此它们的点重叠。这个点有点暗(根据你的 alpha = 0.4)。您可以通过添加 x = jitter(x) 使这一点变得明显(为了演示,您不会在生产中这样做)。鉴于相同的数据,我不确定您希望看到什么。

如果你想要 7 个不同的点,那么我建议你创建 n+1 并删除最后一个(或第一个)点。


circleFun <- function(center = c(-1, 1), diameter = 1, npoints = 7) {
  r <- diameter / 2
  tt <- seq(0, 2 * pi, length.out = npoints + 1)  # changed
  xx <- center[1] + r * cos(tt)
  yy <- center[2] + r * sin(tt)
  data.frame(x = xx, y = yy)[-1,,drop = FALSE]    # changed
}

## unchanged from here on
ej <- 
  circleFun(diameter = 50, center = c(50,50), npoints = 7)
ej |> 
  ggplot(aes(x = x, y = y)) +
  geom_point(alpha = 0.4) +
  theme_bw()

(顺便说一句,不需要显式调用return(.),尤其是当它是函数的唯一端点并且基于数据流“显而易见”时。当然没有伤害,但它增加了调用堆栈上没有增加任何价值的一步。它可能是声明性/自文档化,因此这是一种风格/主观点。)

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多