【问题标题】:Fill geom_tile with a gradient用渐变填充 geom_tile
【发布时间】:2017-10-19 06:04:18
【问题描述】:

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

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)

现在,我想用渐变(中心颜色最浓(column=value)并逐渐淡出到末端(上和下))为图块着色。

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

编辑

渐变应该在图块内,请参阅 Alex Krusz 的这个示例。链接:here

【问题讨论】:

    标签: r ggplot2 gradient


    【解决方案1】:

    我认为 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()
    

    【讨论】:

    • 老实说,我在这个问题上花了这么多时间,无法用 geom_rect 找到任何可靠的渐变,但你的答案是惊人的透明度!
    猜你喜欢
    • 2021-12-05
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2019-05-04
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多