2

I have this network graph in R:

library(igraph)

# create the data frame
my_data <- data.frame(to = c(1,2,3,4,2,4,1,1,1,7,7), from = c(2,2,2,2,6,5,7,8,9, 10,11))

# create the igraph object
my_graph <- graph_from_data_frame(my_data, directed = FALSE)

# plot the graph
plot(my_graph)

In a previous question (All Nodes of Degree "N" that can be reached from Some Node), I learned how to find out the number of nodes that can be reached from a specific node within a radius = n:

# neighbors of degree = 3 from node = 1
q = ego(my_graph, 3, "1")

[[1]]
+ 11/11 vertices, named, from 8e85769:
 [1] 1  2  7  8  9  3  4  6  10 11 5 

My Question: I am trying to plot this "q" object - however, when I try to make a plot, I get the following error:

Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' is a list, but does not have components 'x' and 'y'

I tried to troubleshoot this problem and I realized that this is likely happening because the ego() function is only returning the nodes and not preserving the edge information.

I tried a workaround with the following code:

plot(induced.subgraph(graph=my_graph,vids=as.numeric(q[[1]])))

The code seems to be working, but am I doing this correctly?

zx8754
  • 52,746
  • 12
  • 114
  • 209
stats_noob
  • 5,401
  • 4
  • 27
  • 83
  • You keep using the word "degree" to refer to the _order_ or _radius_ of a neighbourhood. This is confusing, as "degree" has a very specific meaning in graph theory: the number of neighbours. – Szabolcs Mar 03 '23 at 09:09
  • Be sure to check the documentation of the functions you are using. The same doc page describes both `ego()` and `make_ego_graph()`: https://r.igraph.org/reference/ego.html – Szabolcs Mar 03 '23 at 09:21
  • `plot.igraph` requires an object of the class `"igraph"`. Try `>plot.igraph` and >`help(is_igraph(graph))`. Use `class(q)` to check the correct object class. – clp Mar 04 '23 at 09:42

1 Answers1

3

Use make_ego_graph to keep edges and attributes:

make_ego_graph is creates (sub)graphs from all neighborhoods of the given vertices with the given order parameter. This function preserves the vertex, edge and graph attributes.

make_ego_graph (and ego) returns a list of graphs, so you need to take the first object to plot:

q <- make_ego_graph(my_graph, 3, '1')
plot(q[[1]])

enter image description here

Maël
  • 45,206
  • 3
  • 29
  • 67
  • can I request you to have a look at this question https://stackoverflow.com/questions/75607765/ggraph-node-color-and-legend-not-matching – PesKchan Mar 03 '23 at 09:25