Jens Munk
Jens Munk

Reputation: 21

log background gradient ggplot

I need a ggplot2 graph with a specific background in the y direction. Y is also log2 scale going from .25 to 4, midpoint thus 1. Y extremes (.25 and 4) must be red while midpoint (1) must be green.

Diagonal grading of background color of ggplot graph in R got me far and from that I have written this:

## create a diag gradient background
## create a df to supply the background to geom_tile
yseq <- seq(-2,2, length=100)

yseqlog2 <- 2^yseq

df <- expand.grid(x=0:100, y=yseqlog2) # dataframe for all combinations

## plot
bgplot <- ggplot(df, aes(x, y, fill=y)) +      # map fill to y
  geom_tile(alpha = 0.75) +      # let the grid show through a bit
  scale_fill_gradient2(low='red', high='red', mid = 'green',midpoint = 1) +  # choose your colours
  scale_y_continuous(trans = 'log2') # transform y axis to log2

bgplot

That gives me almost what I want, except the low red intensity at .25. See pic. How do I get full red at .25?? Thanks.

/Jens

output showing low red intensity at .25

Upvotes: 1

Views: 832

Answers (1)

bVa
bVa

Reputation: 3938

You can use scale_fill_gradientn :

bgplot <- ggplot(df, aes(x, y, fill = y)) +
  geom_tile(alpha = 0.75) + 
  scale_fill_gradientn(colors = c("red", "green", "red"), 
                       limits = c(0.25, 4), 
                       trans = "log2") +  
  scale_y_continuous(trans = "log2")

enter image description here

Upvotes: 2

Related Questions