简体   繁体   中英

R ggplot2: draw segment between points

How can I use geom_segment to draw lines on plot, after the data have 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"))

Plot the data:

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

plot1

Add faceting:

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

用刻面绘图

I want to draw a segments from the "before" point to the "after" point for each variable. (see mock up image). How can I do this? I tried some things with geom_segment but I kept having errors. Will casting the data into a new data frame help?? Thanks!

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

Final "ideal" plot:

理想的最终情节

You were definitely on the right track with the casted data. Give this a shot:

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)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM