log background gradient ggplot

微笑、不失礼 提交于 2021-01-28 05:51:18

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/50464017/log-background-gradient-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!