Imagine I plot this toy data:
lev <- c("A", "B", "C", "D")
nodes <- data.frame(ord=c(1,1,1,2,2,3,3,4), brand=
factor(c("A", "B", "C","B", "C","D", "B","D"), levels=lev),
thick=c(16,9,9,16,4,1,4,1))
edge <- data.frame(ord1=c(1,1,2,3), brand1=factor(c("C","A","B","B"),
levels=lev),ord2=c(2,2,3,4), brand2=c("C","B","B","D"),
N1=c(2,1,2,1), N2=c(5,5,2,1))
ggplot() +
geom_point(data = nodes,
aes(x = ord, y = brand, size = sqrt(thick)),
color = "black", shape = 16, show.legend = T) +
scale_x_continuous(limits=c(1, 4), breaks=seq(0,4,1),
minor_breaks = NULL) +
geom_segment(data = edge,
aes(x = ord1, y = brand1, xend = ord2, yend = brand2),
color = "blue", size = edge$N2/edge$N1) +
ylim(lev) +
theme_bw()
I would like to add another legend (below the nodes) relating the width of the segments and N2/N1.
PD: Following some of your suggestions...
ggplot() +
geom_segment(data = edge,
aes(x = ord1, y = brand1, xend = ord2, yend = brand2, size = N2/N1),
color = "blue", show.legend = T) +
geom_point(data = nodes,
aes(x = ord, y = brand, size = thick),
color = "black", shape = 16, show.legend = T) +
scale_x_continuous(limits = c(1, 4), breaks = 0:4,
minor_breaks = NULL) +
scale_size_continuous(trans = "sqrt", breaks = c(1,4,9,16)) +
ylim(lev) + theme_bw()
I got the legend but it overlaps with the other one.
I can try using colors instead of widths:
ggplot()+ geom_segment(data=edge, aes(x=ord1, y=brand1, xend=ord2, yend=brand2, alpha=N2/N1) , size=1 ,show.legend = T) +
geom_point(data=nodes,aes(x=ord, y=brand, size=thick), color="black", shape=16,show.legend = T) +
scale_x_continuous(limits=c(1, 4), breaks=seq(0,4,1), minor_breaks = NULL) + scale_size_continuous(trans = "sqrt", breaks=c(1,4,9,16)) +
ylim(lev) + theme_bw()
Though I prefer the original approach with widths because in my real plot I'll have many lines crossing.
PD: Any solution with lattice or any alternative able to be exported as svg or vectorial pdf?
PD2: I've found another problem, thin points aren't scaled properly and sometimes is impossible to force ggplot to show a proper legend: How can I force ggplot to show more levels on the legend?
Using a highly experimental package I put together:
Created on 2018-05-16 by the reprex package (v0.2.0).
Sometimes ggplot may not be the best tool for the job. it pays to be familiar with some other plotting options for these instances, with R's base graphics system being reasonably versatile.
Here's how you might do it in base graphics: