[英]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()
事實上,傳入以下任何字符都會產生一條豎線: "|"
、 "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.