Reputation: 459
I am trying to plot a network graph and show only the labels for the geom_node_text that have a centrality score above a specific threshold. My code is below:
rt_tbl %>%
mutate(centrality = centrality_authority()) %>%
ggraph(layout = 'kk') +
geom_edge_link(aes(), colour = "gray", alpha = 0.5) +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(data=subset(centrality > 0.6), aes(centrality, label=name)) +
theme_graph(base_family = "Roboto Condensed", base_size = 13)
I encounter the following error:
Error in subset(centrality > 100) : object 'centrality' not found
My data looks like this:
# A tbl_graph: 1589 nodes and 3992 edges
# A directed multigraph with 3 components
# Node Data: 1,589 x 3 (active)
name degree centrality
<chr> <dbl> <dbl>
1 Ashinlay1970 35 0.90053429
2 WinTunMin1 25 0.66408597
3 Yaminayeyaohn1 2 0.06080755
4 TUNOO00655880 3 0.07609831
5 inewagency 8 0.21569006
6 KSwe03 4 0.12416238
# ... with 1,583 more rows
# Edge Data: 3,992 x 2
from to
<int> <int>
1 1 48
2 1 49
3 1 1
# ... with 3,989 more rows
Upvotes: 4
Views: 4790
Reputation: 2101
I never used ggraph
before and you should really provide a reproducible minimal example, but try this:
rt_tbl %>%
mutate(centrality = centrality_authority()) %>%
ggraph(layout = 'kk') +
geom_edge_link(aes(), colour = "gray", alpha = 0.5) +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(aes(label=ifelse(centrality > .6, name, NA))) +
theme_graph(base_family = "Roboto Condensed", base_size = 13)
Your subset
-approach does not work because it does not look inside your rt_tbl
but tries to get the object centrality
, which does not exist. But it would not work anyway, because you need to give it a vector of same length as your data, but subset only returns the values that match your condition. Therefore, using ifelse
is better suited for your task.
BTW this is a minimal reproducible example (at least I now know how to use ggraph
):
library(tidygraph)
library(ggraph)
rt_tble <- tidygraph::create_star(10) %>%
mutate(centrality = centrality_authority(),
name = LETTERS[1:10])
ggraph(graph = rt_tble) +
geom_edge_link() +
geom_node_point(aes(size = centrality, colour = centrality)) +
geom_node_text(aes(label = ifelse(centrality > .6, as.character(name), NA_character_)))
I had to use as.character(name)
instead of name
or levels(name)
(as I did before), maybe you would have to change that in my solution above as well...
But regarding that, have a look at @Alper Yilmaz solution below.
Upvotes: 8
Reputation: 329
This is not an answer but a comment for any future visitor using the answer above.
When I tried levels(name)
in different networks it gave erroneous results. tidygraph
has filter
property which can be used in various geoms for filtering nodes, edges, etc.
So, the geom_node_text
line of the answer above should work better if written as:
geom_node_text(aes(filter=centrality > .6, label = name))
Upvotes: 10