R ggplot2:在点之间绘制段

时间:2017-03-18 16:35:59

标签: r ggplot2

在数据与geom_segment融合后,如何使用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 1
library(ggplot2)
ggplot(data_melt, aes(x=variable, y=value, group = time_group)) + 
     geom_point(aes(color = time_group))

plot1

添加分面:

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

Plot with faceting

我想从每个变量的“之前”点到“之后”点绘制一段。 (见模拟图像)。我怎么能这样做?我尝试了geom_segment的一些事情,但我一直有错误。将数据转换成新的数据框有帮助吗?谢谢!

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

最终的“理想”情节:

Ideal Final Plot

1 个答案:

答案 0 :(得分:4)

你肯定在使用已投射数据的正确轨道上。试一试:

new ArrayList<>()

enter image description here