CptNemo
CptNemo

Reputation: 6755

Visualize igraph degree distribution with ggplot2

I want to visualise the degree distribution of an igraph object with ggplot2. Because ggplot2 doesn't take a the simple numeric vector generated by degree() I convert it to a frequency table. Then I pass it to ggplot(). Still I get: geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic? I can't set the table column degree to factors since I need to plot it also on a log scale.

library(igraph)
library(ggplot2)

g <- ba.game(20) 

degree <- degree(g, V(g), mode="in")
degree
# [1] 6 2 7 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0

degree <- data.frame(table(degree))
degree
#   degree Freq
# 1      0   13
# 2      1    4
# 3      2    1
# 4      6    1
# 5      7    1

ggplot(degree, aes(x=degree, y=Freq)) +
  geom_line()
# geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?

Upvotes: 0

Views: 1966

Answers (1)

Brian Diggs
Brian Diggs

Reputation: 58825

The problem is that you have turned degree$degree into a factor by using table. Two things to fix this:

  • make it a factor with all possible values (up to the largest degree) so that you don't miss the zeros.
  • convert the labels back to numbers before plotting

Implementing those (I used degree.df instead of overwriting degree to keep the different steps distinct):

degree.df <- data.frame(table(degree=factor(degree, levels=seq_len(max(degree)))))
degree.df$degree <- as.numeric(as.character(degree.df$degree))

Then the plotting code is what you had:

ggplot(degree.df, aes(x=degree, y=Freq)) +
  geom_line()

enter image description here

Upvotes: 1

Related Questions