Reputation: 1262
How can I get a line with colour gradient (preferably with multiple stops) as an (y)-axis in ggplot?
I want to add this as a colour-coded evaluation hint to a violin plot. 'Good' will be encoded as green, whereas 'bad' should be red.
What I've come up with was to add an geom_segment
to the side, but this doesn't yet work:
R code:
# 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)))
Upvotes: 2
Views: 1085
Reputation: 423
geom_segment
dosen't work here
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)))
Upvotes: 5