dcl*_*dcl 9 plot r graph ranking bipartite
我想知道是否有一种简单的方法来绘制R中有向二分图形式的2个列表之间元素位置的变化.例如,列表1和2是字符串的向量,不一定包含相同的字符串.内容:
list.1 <- c("a","b","c","d","e","f","g")
list.2 <- c("b","x","e","c","z","d","a")
Run Code Online (Sandbox Code Playgroud)
我想生成类似于:

我在使用igraph包时有轻微的抨击,但不能轻易地构建我想要的东西,我想象并希望不应该太难.
干杯.
这是一个简单的功能,可以做你想要的.基本上它用于match匹配从一个向量到另一个向量的元素并arrows绘制箭头.
plotRanks <- function(a, b, labels.offset=0.1, arrow.len=0.1)
{
old.par <- par(mar=c(1,1,1,1))
# Find the length of the vectors
len.1 <- length(a)
len.2 <- length(b)
# Plot two columns of equidistant points
plot(rep(1, len.1), 1:len.1, pch=20, cex=0.8,
xlim=c(0, 3), ylim=c(0, max(len.1, len.2)),
axes=F, xlab="", ylab="") # Remove axes and labels
points(rep(2, len.2), 1:len.2, pch=20, cex=0.8)
# Put labels next to each observation
text(rep(1-labels.offset, len.1), 1:len.1, a)
text(rep(2+labels.offset, len.2), 1:len.2, b)
# Now we need to map where the elements of a are in b
# We use the match function for this job
a.to.b <- match(a, b)
# Now we can draw arrows from the first column to the second
arrows(rep(1.02, len.1), 1:len.1, rep(1.98, len.2), a.to.b,
length=arrow.len, angle=20)
par(old.par)
}
Run Code Online (Sandbox Code Playgroud)
一些示例图
par(mfrow=c(2,2))
plotRanks(c("a","b","c","d","e","f","g"),
c("b","x","e","c","z","d","a"))
plotRanks(sample(LETTERS, 20), sample(LETTERS, 5))
plotRanks(c("a","b","c","d","e","f","g"), 1:10) # No matches
plotRanks(c("a", "b", "c", 1:5), c("a", "b", "c", 1:5)) # All matches
par(mfrow=c(1,1))
Run Code Online (Sandbox Code Playgroud)

这是使用igraph函数的解决方案.
rankchange <- function(list.1, list.2){
grp = c(rep(0,length(list.1)),rep(1,length(list.2)))
m = match(list.1, list.2)
m = m + length(list.1)
pairs = cbind(1:length(list.1), m)
pairs = pairs[!is.na(pairs[,1]),]
pairs = pairs[!is.na(pairs[,2]),]
g = graph.bipartite(grp, as.vector(t(pairs)), directed=TRUE)
V(g)$color = c("red","green")[grp+1]
V(g)$label = c(list.1, list.2)
V(g)$x = grp
V(g)$y = c(length(list.1):1, length(list.2):1)
g
}
Run Code Online (Sandbox Code Playgroud)
这将构建,然后从您的向量绘制图形:
g = rankchange(list.1, list.2)
plot(g)
Run Code Online (Sandbox Code Playgroud)

调整颜色方案和符号以适合使用igraph文档中详述的选项.
请注意,这未经过全面测试(仅针对您的示例数据进行了测试),但您可以看到它是如何根据代码构建二分图的.
使用 ggplot2:
v1 <- c("a","b","c","d","e","f","g")
v2 <- c("b","x","e","c","z","d","a")
o <- 0.05
DF <- data.frame(x = c(rep(1, length(v1)), rep(2, length(v2))),
x1 = c(rep(1 + o, length(v1)), rep(2 - o, length(v2))),
y = c(rev(seq_along(v1)), rev(seq_along(v2))),
g = c(v1, v2))
library(ggplot2)
library(grid)
ggplot(DF, aes(x=x, y=y, group=g, label=g)) +
geom_path(aes(x=x1), arrow = arrow(length = unit(0.02,"npc")),
size=1, color="green") +
geom_text(size=10) +
theme_minimal() +
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
panel.grid = element_blank())
Run Code Online (Sandbox Code Playgroud)

这当然可以很容易地包装在一个函数中。
| 归档时间: |
|
| 查看次数: |
3500 次 |
| 最近记录: |