繁体   English   中英

R 的 ggplot2 中 geom_point 中数据点的垂直线

[英]Vertical Lines for Data Points in geom_point in ggplot2 for R

有什么方法可以将垂直线作为 ggplot2 中的数据点表示? 形状选项 0-25 都不是我想要的,所以我猜我需要另一个加载项或改变形状 15 尺寸的方法。 左图是我想要的示例看起来像。

这里有一些简单的代码,以防它有助于编写响应:

a <- c(1, 3, 5)
b <- c(2, 4, 6)
df <- data.frame(a, b)

ggplot(data = df, aes(x = a, y = b)) +
geom_point(shape = 15)

我看到了两种可能的方法来帮助生成类似于您在引用的 plot 中看到的垂直字形。

第一个是一种解决方法,它使用geom_errorbar() function。 第二个涉及将特定数值传递给shape参数,但在scale_shape_identity() function 的帮助下。

# Reproducing your data

a <- c(1, 3, 5)
b <- c(2, 4, 6)
df <- data.frame(a, b)

# Let's specify the upper and lower limits manually

df <- df %>%
  mutate(
    upper = +0.5 + b,
    lower = -0.5 + b
  )

第一种方法利用geom_errorbar() function,除了我们设置width = 0来抑制水平线。 请注意,我手动设置了上限和下限并将它们附加到您的数据框中。 调整垂直距离以满足您的需要。

# 1st Method

ggplot(data = df, aes(x = a, y = b)) +
  geom_errorbar(aes(ymin = lower, ymax = upper), color = "red", width = 0) +
  theme_classic()

错误栏解决方法

第二种方法直接利用shape参数。 请注意, geom_point()函数的shape参数可容纳各种不同的值。 通常使用从 0 到 25 的形状值,但也存在其他值。 特别是,形状 32 到 127 对应于各种 ASCII 字符。 scale_shape_identity() ,您可以通过任何合法的形状值。 值 73 或 108 应该可以正常工作。

为了提供更深入的了解,我们传递给shape参数的数值也称为 ASCII 码。 特别地,代码73对应于大写字母“I”(即, "I" ),而代码108对应于小写字母“l”(即, "l" )。 在您的 plot 中,字母将出现没有衬线(即横线),将您的所有点转换为竖线。 请参阅下面的演示:

# 2nd Method

ggplot(data = df, aes(x = a, y = b)) + 
  scale_shape_identity() +
  geom_point(shape = 108, size = 10, color = "red") +
  theme_classic()

形状值 108

事实上,传入以下任何字符都会产生一条竖线: "|" "l""I"

# Other possible solutions

geom_point(shape = "I")  # ASCII code 73
geom_point(shape = "l")  # ASCII code 108
geom_point(shape = "|")  # ASCII code 124

暂无
暂无

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

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