I am working with the R programming language. In a previous question (R: Erasing Lines on ggplot2 - drawing half rectangles), I learned how to make the following graph:
library(tidyverse)
var_1 = rnorm(1000,20,20)
var_2 = rnorm(1000,20,20)
my_data = data.frame(var_1, var_2)
ggplot(data=my_data, aes(x=var_1, y=var_2)) +
geom_point() +
geom_segment(aes(x = -50, xend = 0, y = 0, yend = 0), color = "red") +
geom_segment(aes(x = 0, xend = 0, y = 0, yend = -50), color = "red") +
geom_segment(aes(x = -50, xend = 50, y = 50, yend = 50), color = "red") +
geom_segment(aes(x = 50, xend = 50, y = 50, yend = -50), color = "red")
I want to change the above code so that "x", "xend", "y", "yend" can come from a data frame:
For instance, suppose I have the following data frame:
my_points = data.frame(x1 = c(-40, -41) , x2 = c(20, 21) , y1 = c(-30, -31), y2 = c(50, 51) )
> my_points
x1 x2 y1 y2
1 -40 20 -30 50
2 -41 21 -31 51
From here, I would like to make two graphs:
ggplot(data=my_data, aes(x=var_1, y=var_2)) +
geom_point() +
geom_segment(aes(x = my_points[1,1], xend = my_points[1,2], y = my_points[1,3], yend = my_points[1,4]), color = "red") +
geom_segment(aes(x = my_points[1,2], xend = my_points[1,1], y = my_points[1,4], yend = my_points[1,3]), color = "red") +
geom_segment(aes(x = my_points[1,1], xend = my_points[1,2], y = my_points[1,4], yend = my_points[1,3]), color = "red") +
geom_segment(aes(x = my_points[1,1], xend = my_points[1,2], y = my_points[1,4], yend = my_points[1,3]), color = "red") + ggtitle("graph 1")
ggplot(data=my_data, aes(x=var_1, y=var_2)) +
geom_point() +
geom_segment(aes(x = my_points[2,1], xend = my_points[2,2], y = my_points[2,3], yend = my_points[2,4]), color = "red") +
geom_segment(aes(x = my_points[2,2], xend = my_points[2,1], y = my_points[2,4], yend = my_points[2,3]), color = "red") +
geom_segment(aes(x = my_points[2,1], xend = my_points[2,2], y = my_points[2,4], yend = my_points[2,3]), color = "red") +
geom_segment(aes(x = my_points[2,1], xend = my_points[2,2], y = my_points[2,4], yend = my_points[2,3]), color = "red") + ggtitle("graph 2")
But this is not producing the same result as before:
Furthermore, Graph 2 also does not work:
Can someone please show me how to fix this?
Thanks!







