Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

r - Connect ggplot boxplots using lines and multiple factor

I'm trying to connect ggplot2 boxplots with geom_lines for multiple factors. I'd been able to accomplish so far to connect all the boxplot with lines, see attach picture. But I wish to connect the only boxplots by their corresponding factor.

enter image description here

For example for my variable FL, I want to connect only those two boxplot, without connecting them with the remaining variables. Similarly for the variable RW, connecting those two sex boxplot without the remaining others.

library("MASS")  
data(crabs)  
melt_crabs <- melt(crabs,id.var=c("sp","sex","index"))   
ggplot(melt_crabs, aes(x = variable, y = value)) +   geom_line(aes(group = index), size = 0.05, alpha = 0.7) +   geom_boxplot(aes(fill = sp), alpha = 0.5) + facet_grid(sex~.)

Does anyone know how to achieve this? I hope I'd explain myself the most clear way.

Many thanks and best wishes,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't know of way to connect the points in exactly the plot that you produced. But I can show you how to do something similar.

The difficulty is that all the points that belong to a pair of boxplots share the same x-coordinate (that is, the same value for variable). Therefore I have used interaction(sex, variable) as the x-coordinate, such that each boxplot has its own x-value. This means, however, that the paired boxplots are less visible. On the other hand, the connecting lines work in the other direction.

In order to plot the lines, they are grouped by interaction(index, variable), which means that data points are connected, when they share the same values for index and variable.

Enough talk, here's the code:

ggplot(melt_crabs, aes(x = interaction(sex, variable), y = value)) +
    geom_boxplot(aes(fill = sex), alpha = 0.5) +
    geom_line(aes(group = interaction(index, variable)),
              alpha = 0.5, colour = "darkgrey") +
    facet_grid(sp~.) +
    scale_x_discrete(labels = rep(levels(melt_crabs$variable), each = 2))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...