Diagonal grading of background color of ggplot gra

2019-09-09 22:26发布

问题:

I am looking to do a graph in the following style, with a fading background. More specifically, I hope to get a diagonal fading

I have already made the graph as so:

ggplot(Data) +
  aes(x=Data$log.avg, y=Data$CoV) +
  geom_point(alpha = 0.3) +
  ggtitle("Oversigt over udbetalingskonti") +
  geom_text(aes(label=ifelse(Data$log.avg > 1.6 | Data$CoV > 2 &
  Data$log.avg > -0.5 , as.character(Data$KT),'')),hjust=-0.2, vjust=-0.2, size=3) +
 labs(x="Avg",y="Coefficient of Variation") 

回答1:

This basic approach helped me with a similar problem.

## create a diag gradient background
## create a df to supply the background to geom_tile
df <- expand.grid(x=-100:100, y=-100:100)     # dataframe for all combinations

## plot
ggplot(df, aes(x, y, fill=x+y)) +      # map fill to the sum of x & y
  geom_tile(alpha = 0.75) +      # let the grid show through a bit
  scale_fill_gradient(low='light blue', high='steelblue4')     # choose your colors

Result:

Consider the following:

`aes(x, y, fill=x+y)` # darkest in the top right corner
`aes(x, y, fill=y-x)` # darkest in the top left corner

To be used in combo with switches to the high & low arguments in scale_fill_gradient



标签: r ggplot2