I want to show the connections between a number of people, organizations or whatever:
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
I couldn't find any examples for this kind of plot, so I started from scratch. However, I'm struggling with the labels for the frequency values. Any ideas how to fix that?
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