Bipartite network graph with ggplot2

安稳与你 提交于 2019-12-03 08:11:31

A simple ggplot2 version of your graph is possible by using geom_segment() and transforming the data much like you did for the base graphics version. I've also included an arguably more polished version, using some of the more advanced customization options in ggplot2.

# Using ggplot2 version 0.9.2.1
library(ggplot2)

dat$x1_norm = rangeTransform(as.integer(dat$X1))
dat$x2_norm = rangeTransform(as.integer(dat$X2))

dat$y1 = 0
dat$y2 = 1

# Simple version.
p1 = ggplot(dat, aes(x=x1_norm, xend=x2_norm, y=y1, yend=y2, colour=X1)) +
     geom_segment(size=1.2) +
     scale_colour_brewer(palette="Set1", name="Person")

ggsave(plot=p1, filename="plot_1.png", height=3.5, width=6)

# Fancy version.
# Create separate data.frames to manually specify axis ticks and axis text.
axis_1 = data.frame(x=rangeTransform(as.integer(unique(dat$X1))),
                    y=0, label=as.character(unique(dat$X1)))

axis_2 = data.frame(x=rangeTransform(as.integer(unique(dat$X2))),
                    y=1, label=as.character(unique(dat$X2)))

p2 = ggplot(data=dat) +
     theme_bw() +
     theme(axis.title=element_blank()) +
     theme(axis.text=element_blank()) +
     theme(axis.ticks=element_blank()) +
     theme(panel.grid=element_blank()) +
     geom_segment(aes(x=x1_norm, xend=x2_norm, y=y1, yend=y2, colour=X1),
                  size=1.2) +
     geom_segment(x=0, xend=1, y=0, yend=0, size=0.7) +
     geom_segment(x=0, xend=1, y=1, yend=1, size=0.7) +
     scale_colour_brewer(palette="Set1", name="Person") +
     scale_y_continuous(limits=c(-0.2, 1.2), expand=c(0, 0)) +
     geom_segment(data=axis_1, aes(x=x, xend=x, y=y, yend=y-0.025), size=0.7) +
     geom_segment(data=axis_2, aes(x=x, xend=x, y=y, yend=y+0.025), size=0.7) +
     geom_text(data=axis_1, aes(label=label, x=x, y=y - 0.075)) +
     geom_text(data=axis_2, aes(label=label, x=x, y=y + 0.075))

ggsave(plot=p2, filename="plot_2.png", height=3.5, width=6)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!