用渐变填充geom_tile

用渐变填充geom_tile

问题描述:

我想创建一个渐变图。我以为用渐变填充我的geom_tile。然而,R不断告诉我,Error: Discrete value supplied to continuous scale用渐变填充geom_tile

df <- data.frame(value=c(55, 40, 5), 
      zz=c("A", "B", "C")) 

df$lower <- df$value-2.9 
df$upper <- df$value+2.9 
ggplot(df, aes(x=zz, y=value, fill=zz))+ 
    geom_tile(aes(x=zz, y=value, fill=zz), width=0.2,height=2.9) 

enter image description here

现在,我想颜色瓷砖用梯度(最密集的着色在中心处(柱=值)和淡出到的端部(上部&更低)。

我怎样才能做到这一点?是geom_tile正确geom这个? 感谢

编辑

渐变应该在瓦片内,请参阅Alex Krusz的这个例子。链接:here enter image description here

我不认为ggplot是用于这种用途,但这里有一种方法来模拟透明度渐变。

创建插值透明度值的数据集:

library(data.table) 

df <- setDT(df) 
n <- 100 
df.lower <- df[, .(ymin = seq(lower, value, length.out = n + 1)[1:n], 
        ymax = seq(lower, value, length.out = n + 1)[2:(n+1)], 
        alpha = seq(0, 1, length.out = n)), by = .(zz)] 
df.upper <- df[, .(ymin = seq(value, upper, length.out = n + 1)[1:n], 
        ymax = seq(value, upper, length.out = n + 1)[2:(n+1)], 
        alpha = seq(1, 0, length.out = n)), by = .(zz)] 
df.new <- rbind(df.lower, df.upper) 
df.new$x <- as.integer(df.new$zz) 
df.new$xmin <- df.new$x - 0.2 
df.new$xmax <- df.new$x + 0.2 

> df.new 
    zz ymin ymax  alpha x xmin xmax 
    1: A 52.100 52.129 0.00000000 1 0.8 1.2 
    2: A 52.129 52.158 0.01010101 1 0.8 1.2 
    3: A 52.158 52.187 0.02020202 1 0.8 1.2 
    4: A 52.187 52.216 0.03030303 1 0.8 1.2 
    5: A 52.216 52.245 0.04040404 1 0.8 1.2 
---           
596: C 7.755 7.784 0.04040404 3 2.8 3.2 
597: C 7.784 7.813 0.03030303 3 2.8 3.2 
598: C 7.813 7.842 0.02020202 3 2.8 3.2 
599: C 7.842 7.871 0.01010101 3 2.8 3.2 
600: C 7.871 7.900 0.00000000 3 2.8 3.2 

叠加的结果:

ggplot() + 
    geom_rect(data = df.new, 
      aes(xmin = xmin, xmax = xmax, 
       ymin = ymin, ymax = ymax, 
       alpha = alpha, fill = zz)) + 
    scale_x_continuous(breaks = as.integer(df$zz), 
        labels = df$zz) + 
    scale_alpha_identity() + 
    theme_bw() 

plot

+0

老实说,我已经在这个问题上花了这么多时间和进不来使用geom_rect为渐变添加任何东西,但是您的答案在透明度方面非常出色! – amrrs