颜色渐变线作为轴

时间:2014-07-30 11:57:25

标签: r ggplot2

如何在ggplot中使用颜色渐变线(最好有多个停靠点)作为(y)-axis?

我想将此作为彩色编码的评价提示添加到小提琴情节中。 '好'将编码为绿色,而“坏”编号为“绿色”。应该是红色的。

我想出的是在旁边添加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)))

enter image description here

1 个答案:

答案 0 :(得分:5)

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)))

enter image description here