首先,我們準備一些與我正在使用的資料非常相似的玩具資料。
rawdata <- data.frame(Score = rnorm(1000, seq(1, 0, length.out = 10), sd = 1),
Group = rep(LETTERS[1:3], 10000))
stdev <- c(10.78,10.51,9.42)
現在我們通過 繪制估計的密度geom_density_ridges。我還通過在零附近添加了一個灰色高光geom_rect。我也用 翻轉圖表coord_flip。
p <- ggplot(rawdata, aes(x = Score, y = Group))
scale_y_discrete()
geom_rect(inherit.aes = FALSE, mapping = aes(ymin = 0, ymax = Inf, xmin = -0.1 * min(stdev), xmax = 0.1 * max(stdev)),
fill = "grey", alpha = 0.5)
geom_density_ridges(aes(fill = Group), scale = 0.5, size = 1, alpha=0.5)
scale_color_manual(values = col)
scale_fill_manual(values = col)
labs(title="Toy Graph", y="Group", x="Value")
coord_flip(xlim = c(-8, 8), ylim = NULL, expand = TRUE, clip = "on")
p
這就是我得到的解決方案,這與我的預期很接近,盡管 y 軸與 x 軸中第一個因素的開始之間存在巨大差距的細節A。我嘗試按照其他帖子的一些建議使用expand=c(0,0)inside scale_y_discrete(),但這并沒有使差距變小。如果可能的話,我仍然希望有一定的差距,盡管很小。我也一直在嘗試翻轉 y 軸上的密度,因此間隙由第一因子密度圖填充,但我沒有成功,因為它似乎并不像人們想象的那樣微不足道。
抱歉,我知道這在技術上可能是兩個不同的問題,“如何減少從 y 軸到第一個密度圖的間隙?” 和“如何從 y 軸翻轉密度以減少間隙?” 但我對第一個問題真的很滿意,因為我知道第二個問題似乎不那么直接。
提前致謝!任何幫助表示贊賞。
uj5u.com熱心網友回復:
翻轉密度也有效地減少了空間,所以這可能就是你需要做的。您可以使用負scale引數來實作它:
ggplot(rawdata, aes(x = Score, y = Group))
scale_y_discrete()
geom_rect(inherit.aes = FALSE,
mapping = aes(ymin = 0, ymax = Inf,
xmin = -0.1 * min(stdev),
xmax = 0.1 * max(stdev)),
fill = "grey", alpha = 0.5)
geom_density_ridges(aes(fill = Group), scale = -0.5, size = 1, alpha = 0.5)
scale_color_manual(values = col)
scale_fill_manual(values = col)
labs(title = "Toy Graph", y = "Group", x = "Value")
coord_flip(xlim = c(-8, 8), ylim = NULL, expand = TRUE, clip = "on")

如果你想保持密度指向相同的方向,但只是減少左側的空間,只需在你的 中設定硬限制coord_flip,不要擴展:
ggplot(rawdata, aes(x = Score, y = Group))
geom_rect(inherit.aes = FALSE,
mapping = aes(ymin = 0, ymax = Inf,
xmin = -0.1 * min(stdev),
xmax = 0.1 * max(stdev)),
fill = "grey", alpha = 0.5)
geom_density_ridges(aes(fill = Group), scale = 0.5, size = 1, alpha = 0.5)
scale_color_manual(values = col)
scale_fill_manual(values = col)
scale_y_discrete()
labs(title = "Toy Graph", y = "Group", x = "Value")
coord_flip(xlim = c(-8, 8), ylim = c(0.8, 4), expand = FALSE)

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533297.html
標籤:rggplot2
上一篇:在列中居中專案
