我正在嘗試將線段間隔添加到ggplot. 但是,我試圖使線段成為漸變,在間隔的每一端將 alpha 淡化為零。
例如,如果我創建一個包含一些間隔的圖,如下所示:
library(ggplot2)
library(dplyr)
df <- data.frame(
name = c('x1', 'x2', 'x3'),
value = c(0.251, 0.207, 0.182),
seg = c(0.027, 0.028, 0.049)
)
p <- df %>%
ggplot() aes(x=name, y=value)
geom_segment(aes(x=name, xend=name, y=(value - seg), yend=(value seg),
col = name),
size = 5)
geom_point(aes(x=name, y = value), shape = 18, size = 5, color = "black")
theme_bw()
xlab('Name')
ylab("Value")
p
這會產生一個像這樣的情節:

但是,我試圖找出一種方法將這些線段變成更粗的條形,從而在每一端將 alpha 淡化為零。
類似于下面的圖(可以在
為清楚起見,我只是想從上圖中重新創建彩色漸變間隔。
編輯
根據其中一條評論,我嘗試使用geom_link它...但我似乎無法讓它正常作業。
To begin, I created a vector of alpha values to pass to geom_link like so:
alpLow <- seq(from = 0, to = 1, length.out = 150)
alpHigh <- rev(alpLow)
alp <- c(alpLow, alpHigh)
And then used this in geom_link:
p <- df %>%
ggplot() aes(x=name, y=value)
geom_link(aes(x = name, y = (value - seg),
xend = name, yend = (value seg),
colour = stat(index)), lineend = "round", size = 5, alpha = alp)
Which produces this:

As you can see, it only applies the gradient at the start and end of the 1st and last line segment.
Furthermore, Im not entirely pleased with the aesthetic of using geom_link as it seems to link together points (which are visible when you zoom in)... I was really hoping for a solid bar that fades the alpha.
uj5u.com熱心網友回復:
我希望下面的內容足夠不同,值得一個新的答案。我有更多時間查看您提供的鏈接。{ggdist} 具有這些梯度間隔統計資料 - 他們需要基礎資料而不是匯總資料來計算其密度。
假設您以某種方式匯總資料,這些值代表您的資料的分布(例如,正態分布),您可以使用它來根據這些值重新創建資料。我在這里為每個組創建了正態分布,使用您的值作為平均值和標準差,然后您可以使用ggdist::stat_gradientinterval. 但是您當然也可以創建其他發行版。
library(tidyverse)
library(ggdist)
df <- data.frame(
name = c('x1', 'x2', 'x3'),
value = c(0.251, 0.207, 0.182),
seg = c(0.027, 0.028, 0.049)
)
df_norm <-
df %>%
split(., .$name) %>%
map(function(x) rnorm(100, x$value, x$seg)) %>%
bind_rows() %>%
pivot_longer(everything(), names_to = "name", values_to = "value")
ggplot(df_norm, aes(x=name, y=value, fill= name))
ggdist::stat_gradientinterval()
theme_bw()
labs(x= 'Name', y = "Value")

由
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371934.html
