R ggplot2: draw a segment between points

How can I use geom_segmentto draw lines on a graph after the data has been melted with reshape2?

# Tiny dataset
facet_group <- c("facet1", "facet1", "facet2", "facet2")
time_group <- c("before", "after", "before", "after")
variable1 <- c(1,5,4,7)
variable2 <- c(2,4,5,8)
variable3 <- c(4,5,6,7)
data <- data.frame(facet_group, time_group, variable1, variable2, variable3)

# Melt data
library(reshape2)
data_melt <- melt(data, id.vars = c("facet_group", "time_group"))

Highlight data:

# Plot 1
library(ggplot2)
ggplot(data_melt, aes(x=variable, y=value, group = time_group)) + 
     geom_point(aes(color = time_group))

plot1

Add cut:

# Plot 2
    ggplot(data_melt, aes(x=variable, y=value, group = time_group)) +
        geom_point(aes(color = time_group)) +
        facet_grid(facet_group ~ .) 

Cutting Area

I want to draw segments from the “before” point to the “after” point for each variable. (see image layout). How can i do this? I tried some things with geom_segment, but I had errors. Will casting data into a new data frame? Thank!

data_cast <- dcast(data_melt, variable + facet_group ~ time_group)

Final "perfect" plot:

Ideal End Site

+4
source share
1 answer

You were definitely on the right track with cast data. Take a picture:

ggplot(data_melt, aes(x=variable, y=value)) +
  geom_point(aes(color = time_group)) + 
  facet_grid(facet_group ~ .) +
  geom_segment(data = data_cast, aes(x = variable, xend = variable, 
                                     y = before, yend = after), 
               arrow = arrow(), 
               colour = "#FF3EFF", 
               size = 1.25)

enter image description here

+4
source

Source: https://habr.com/ru/post/1672635/


All Articles