简体   繁体   English

ggplot2 没有 plot 所有点

[英]ggplot2 doesn't plot all the points

I am trying to make a graph in ggplot2 of 7 points in the shape of a circle, but trying to graph them only shows me 6 and I don't know why this happens.我正在尝试在 ggplot2 中绘制一个圆形 7 个点的图形,但尝试绘制它们只显示 6 个,我不知道为什么会这样。

The code is the following:代码如下:

# 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()

Does anyone know why this happens?有谁知道为什么会这样?

Rows 1 and 7 are identical, so their points are overlapped.第 1 行和第 7 行相同,因此它们的点重叠。 The dot is a bit darker (per your alpha = 0.4).这个点有点暗(根据你的 alpha = 0.4)。 You can make this obvious by adding x = jitter(x) (For demonstration, not that you'd do that in production).您可以通过添加 x = jitter(x) 来使这一点变得明显(为了演示,您不会在生产中这样做)。 I'm not sure what you're expecting to see given the identical data.鉴于相同的数据,我不确定您期望看到什么。

If you want 7 distinct points, then I suggest you create n+1 and remove the last (or first) point.如果你想要 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()

在此处输入图像描述

(BTW, there is no need for an explicit call to return(.) , especially when it is the only end-point of the function and "obvious" based on data flow. It certainly doesn't hurt, but it adds one step on the call stack that adds no value. It may be declarative/self-documenting, and as such this is a style/subjective point.) (顺便说一句,不需要显式调用return(.) ,尤其是当它是 function 的唯一端点并且基于数据流“显而易见”时。当然没有什么坏处,但它增加了一步在没有增加任何价值的调用堆栈上。它可能是声明性/自我记录的,因此这是一个风格/主观点。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM