ggplot - abline disappears when limiting x and y

时间:2018-11-13 07:52:27

标签: r ggplot2

I have the following data:

set.seed(123456)
Test_1 <- round(rnorm(20,mean=40,sd=5),0)/100
Test_2 <- round(rnorm(20,mean=60,sd=5),0)/100
ei.data <- as.data.frame(cbind(Test_1,Test_2))

 intercept <- as.data.frame(matrix(0,20,1))
  slope <- as.data.frame(matrix(0,20,1))
  data <- cbind(intercept,slope)
  colnames(data) <- c("intercept","slope")
  for (i in 1:nrow(ei.data)){
    data[i,1] <- (ei.data[i,2]/(1-ei.data[i,1]))
    data[i,2] <- (ei.data[i,2]/(1-ei.data[i,2]))
  }

Now I want to plot the data from the ei.data data frame in a point plot and then add the date from the data data frame in form of lines using abline.

ei <- ggplot(ei.data, aes(Test_1,Test_2))+
  geom_point()+
  theme_bw()+
  scale_y_continuous(limits = c(0, 1))+
  scale_x_continuous(limits = c(0, 1))+
  geom_abline(slope =data[1,2] , intercept =data[1,1])
ei

However, the problem I have is, that if I limit x and y scale to [0,1] the line I created using abline disappears. How can I still plot the lines even when I am limiting x and y?

1 个答案:

答案 0 :(得分:1)

正如您对问题的评论所言,放大您所在地区的那部分将使您的退位始终最大程度地消失。因此,这个答案可能不是100%令人满意的。不过,您仍然可以更改限制,也可以突出显示abline的一小部分,以便在不更改限制的情况下更容易看到它。

这是一个例子:

# Changing the limits
ggplot(ei.data, aes(Test_1,Test_2))+
  geom_point()+
  theme_bw()+
  scale_y_continuous(limits = c(0, 2))+
  scale_x_continuous(limits = c(0, 2))+
  geom_abline(slope =data[1,2] , intercept =data[1,1])

enter image description here

# Not changing the limits, but making it visible more easily
ggplot(ei.data, aes(Test_1,Test_2))+
  geom_point()+
  theme_bw()+
  scale_y_continuous(limits = c(0, 1))+
  scale_x_continuous(limits = c(0, 1))+
  geom_abline(slope =data[1,2] , intercept =data[1,1],
              color="red", size=2)+
  geom_segment(aes(x = 0.2, y = 0.75, xend = 0.05, yend = 0.9),
               colour='red', size=2,arrow = arrow(length = unit(0.5, "cm")))+
  annotate("text", label="Mind the abline!", x=0.25, y=0.74)

enter image description here