想象一下我绘制这个玩具数据:
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 get this plot, as expected.
我想添加另一个与线段宽度和 N2/N1 有关的图例(在节点下方)。
PD:
根据您的一些建议...
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()
我得到了图例,但它与另一个重叠。
我可以尝试使用颜色而不是宽度:
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()
Or varying alpha
尽管我更喜欢原始的宽度方法,因为在我的真实图中,我会有很多线交叉。
PD:任何带有点阵的解决方案或任何能够导出为 svg 或矢量 pdf 的替代方案?
PD2:我发现了另一个问题,细点没有正确缩放,有时不可能强制 ggplot 显示正确的图例:如何强制 ggplot 在图例上显示更多级别?