我正在尝试绘制双字母组(来自Text Mining with R)的同现,如下所示:
但是按照书中给出的完全相同的代码,我的绘图缺少许多线条和颜色。不知道是因为我错过了一些重要步骤还是缺少某些软件包。
以下是用于说明的简单版本:
library(dplyr)
library(ggplot2)
library(igraph)
library(ggraph)
terms <- sample(letters[1:10],50,replace=T)
count <- sample(1:50,25,replace=T)
bigrams <- data_frame(term1=terms[1:25],term2=terms[26:50],occur=count) %>%
arrange(desc(occur)) %>%
graph_from_data_frame()
a <- grid::arrow(type = "closed", length = unit(.15, "inches"))
我得到的图不正确(甚至图例未正确显示):
ggraph(bigrams, layout = "fr") +
geom_edge_link(aes(edge_alpha = occur), show.legend = FALSE,
arrow = a, end_cap = circle(.07, 'inches')) +
geom_node_point(color = "lightblue", size = 5) +
geom_node_text(aes(label = name), vjust = 1, hjust = 1) +
theme_void()
ggraph(bigrams, layout = "fr") +
geom_edge_link(aes(edge_alpha = occur, edge_width = occur), edge_colour = "cyan4") +
geom_node_point(size = 5) +
geom_node_text(aes(label = name), repel = TRUE,
point.padding = unit(0.2, "lines")) +
theme_void()
好吧,这很有趣,但是删除theme_void()
可以解决所有问题。我想这本书写的时候会有所不同。但是,第二张图中的图例仍未显示,因此仍然存在错误:
答案 0 :(得分:2)
我发现ggraph软件包不错,但存在一些问题。对我来说,如果您在RStudio中放大绘图,代码就可以工作。
但是,我建议您使用一些小的mod,使其在不缩放的情况下进行绘制:
ggraph(bigrams, layout = "fr") +
geom_edge_link(aes(width = occur), # seems the alpha creates problem with legend
colour = "cyan4") +
geom_node_point(size = 5) +
scale_edge_width(range = c(0.2, 2)) + # rescale the edges
geom_node_text(aes(label = name), repel = TRUE, point.padding = unit(0.2, "lines"))+
theme_graph() # made for graph
如果您想要Alpha,可以尝试一下,但是我注意到您仅在RStudio中看到图例:
数据与您相同,但使用set.seed(1)
。