在ggplot背景中的对角渐变

时间:2017-09-21 23:11:09

标签: r ggplot2

这就是我需要我的情节的样子 This is how I need my plot to look like

您好我正在尝试使用Diagonal渐变来绘制。到目前为止,我已经完成了这个情节,但不知道如何设置背景。有人可以帮帮我吗?

到目前为止这是我的代码......

library(ggplot2)
ggplot(PSA, aes(y = Susc, x = Prod)) +
    geom_point()+ 
    geom_text_repel(aes(label=Name), size = 3)+
    xlab('Productivity') + ylab("Susceptibility")+
    theme(axis.line.x=element_line(),
    axis.line.y=element_line())+ 
    xlim(3, 1)+ ylim(1,3)+
    theme_bw() +
    theme(panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(),
    panel.background = element_rect(colour = "black", size=0.5))

这是数据:

BRF       2.300   1.496
CAB       2.125   1.388
CHRF      1.800   1.493
CRF       1.900   1.723
KG        2.200   1.564
LING      1.875   1.424
QRF       1.500   1.865
RIL       2.833   1.801
RSP       2.286   1.693

1 个答案:

答案 0 :(得分:1)

我会通过构造球体轮廓来使用geom_raster。这是我通过修改现有代码得到的。

PSA <- read.table(text="BRF       2.300   1.496
CAB       2.125   1.388
                 CHRF      1.800   1.493
                 CRF       1.900   1.723
                 KG        2.200   1.564
                 LING      1.875   1.424
                 QRF       1.500   1.865
                 RIL       2.833   1.801
                 RSP       2.286   1.693
                 ")

colnames(PSA)<-c("Name","Prod","Susc")

library(ggplot2)
library(viridis)

# Constructing a contour of circles
xColor <- seq(0,1,length.out=100) # scale of color for x and y, 
yColor <- seq(0,1,length.out=100)
x <- seq(3,1,length.out=100) # on respective x and y axis
y <- seq(1,3,length.out=100)
df <- cbind(expand.grid(x=xColor, y=yColor), expand.grid(x=x, y=y)) #grid for colors
colnames(df)<-c("xColor","yColor","x","y")
df$zColor <- (df$xColor^2+df$yColor^2) # the color factor for radius


ggplot(data=PSA,aes(y = Susc, x = Prod))+  
  geom_raster(data =df, aes(x, y,fill = zColor))+
  scale_fill_distiller(type = "div", palette = 8, direction=-1)+ # if you really want Green-Yellow-Red
  # scale_fill_gradient(low = "green", high = "red")+ # other color schemes
  # scale_fill_viridis(direction=-1)+
  geom_point()+
  geom_text(data=PSA,aes(label=Name), size = 3)+ # temp!- instead of geom_text_repel 
  xlab('Productivity') + ylab("Susceptibility")+
  theme(axis.line.x=element_line(),
        axis.line.y=element_line())+ 
  xlim(3, 1)+ ylim(1,3)+
  coord_cartesian(expand = F) + # no padding for border
  theme_bw() +
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(),
        panel.background = element_rect(colour = "black", size=1),
        legend.position="none") # removing legend for raster