【问题标题】:Colour gradient line as axis颜色渐变线为轴
【发布时间】:2014-07-30 11:57:25
【问题描述】:

如何在 ggplot 中获得一条颜色渐变(最好有多个停止点)作为 (y) 轴的线?

我想将此作为颜色编码的评估提示添加到小提琴图。 “好”将编码为绿色,而“坏”应编码为红色。

我想出的是在旁边添加一个geom_segment,但这还行不通:

  • 没有渐变颜色,只有一种颜色,从给定范围内随机选择
    (在这种情况下是一些浅绿色)
  • 将轴手动设置为一条线感觉不对 - 应该有一些自动的东西


R 代码:

# create some test data
type_list <- c("first", "second", "third")
test_data <- data.frame()

N <- 16
for( i in 1:length(type_list))
{
    test_data = rbind( test_data,
                       data.frame(
                           idx  = 1:N,
                           vals = runif( n = N, min = 0, max = 1),
                           type = type_list[i]
                       )
   )
}

# plot data as violin 
ggplot( test_data, aes( y = vals, fill = type)) +
    geom_violin( aes( x = type )) +
    geom_segment( aes(x = 0, xend = 0, y = 0, yend = 1, color = vals, size = 2))+
    scale_colour_gradientn( colours = c( "darkred", "yellow", "darkgreen"),
                            breaks  = c( 0, 0.5, 1),
                            labels  = c( "bad", "medium", "good"),
                            limits  = c( 0,1)) + 
    guides( size = FALSE, colour = guide_legend( title="Evaluation", reverse = TRUE, 
                                                 override.aes = list( size = 5)))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    geom_segment 在这里不工作

    ggplot( test_data, aes( y = vals)) +
      geom_violin( aes( x = type, fill = type )) +
      geom_line(data = data.frame(x = c(rep(0,100)), y = seq(0,1,length.out=100)), aes(x=x, y=y, color=y),size=2)+
      scale_colour_gradientn( colours = c( "darkred", "yellow", "darkgreen"),
                              breaks  = c( 0, 0.5, 1),
                              labels  = c( "bad", "medium", "good"),
                              limits  = c( 0,1)) + 
      guides( size = FALSE, colour = guide_legend( title="Evaluation", reverse = TRUE, 
                                                   override.aes = list( size = 5)))
    

    【讨论】:

    • 像魅力一样工作,谢谢。不过,您知道更优雅的解决方案吗?
    • 您认为建议的解决方案有什么不雅之处?对geom_linescale_colour_gradientn 的一次调用对我来说似乎很少。
    • @drammock:事实是我必须调整值范围并打破。否则很容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 2020-05-29
    • 2014-10-26
    • 1970-01-01
    • 2020-09-11
    相关资源
    最近更新 更多