我想展示一些人,组织或其他人之间的联系:
Var1 Var2 Freq
1 F A 5
2 F B 38
3 B C 10
4 E C 28
5 A D 8
6 B D 21
7 A E 50
8 A F 34
9 D F 50
10 E F 14
我找不到这种情节的任何例子,所以我从头开始。但是,我正在努力争取频率值的标签。任何想法如何解决?
MWE:
### Sample data ###
# Gerate names
names <- LETTERS[1:6]
# Generate all possible permutations
df = expand.grid(rep(list(names), 2))
rownames(df) <- NULL
# Drop some of the permutations
df <- df[df$Var1 != df$Var2, ]
df <- df[-sample(1:nrow(df), nrow(df) * 2/3), ]
# Add a column with random frequency values
df$Freq <- sample(1:50, nrow(df), replace=T)
### Prepare sample data for ggplot ####
# Add a column with the row numbers (used for grouping)
df$Pair <- 1:nrow(df)
# Convert data frame to long format
df.from <- df[, -which(names(df) %in% c("Var2"))]
df.from$Type <- "From"
colnames(df.from) <- c("Name", "Freq", "Pair", "Type")
df.to <- df[, -which(names(df) %in% c("Var1"))]
df.to$Type <- "To"
colnames(df.to) <- c("Name", "Freq", "Pair", "Type")
df2 <- rbind(df.from, df.to)
### Plot ###
library(ggplot2)
library(scales)
p <- ggplot()
p <- p + geom_text(aes(x = "From", y = names, label = names), hjust = 1, vjust = 0.5)
p <- p + geom_text(aes(x = "To", y = names, label = names), hjust = 0, vjust = 0.5)
p <- p + geom_line(data = df2, aes(x = Type, y = Name, group = Pair))
p <- p + geom_text(data = df2[df2$Type == "To", ], aes(x = Type, y = Name, group = Pair, label = Freq), hjust = 3, vjust = 0.5)
p <- p + scale_y_discrete(name = "", limits = rev(factor(names, levels = sort(names))))
p <- p + scale_x_discrete(name = "", limits = c("From", "To"))
p
答案 0 :(得分:3)
请求:
显示许多人,组织或其他任何人之间的联系
听起来像是想要绘制网络图。使用network
包:
#Construct a sparse graph
m<-matrix(rbinom(100,1,1.5/9),10)
diag(m)<-0
g<-network(m)
#Plot the graph
plot(g)
您可以获得以下内容
或者,这可能与您的问题更相关,您可以考虑使用qgraph
包。例如下面的代码:
require(qgraph)
set.seed(1)
adj = matrix(sample(0:1, 10^2, TRUE, prob = c(0.8, 0.2)), nrow = 10, ncol = 10)
qgraph(adj)
title("Unweighted and directed graphs", line = 2.5)
会返回这个漂亮的网络图:
如果您正在寻找更多示例,请参阅Sacha Epskam的this excellent page,了解如何使用qgraph
。