Created
February 19, 2011 02:34
-
-
Save kjhealy/834774 to your computer and use it in GitHub Desktop.
Align labels nicely in circular igraph plots
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Here's one way to do it. | |
library(igraph) | |
library(ggplot2) | |
## The igraph docs say that vertex.label.degree controls the position | |
## of the labels with respect to the vertices. It's interpreted as a | |
## radian, like this: | |
## | |
## Value is : Label appears ... the node | |
## -pi/2: above | |
## 0: to the right of | |
## pi/2: below | |
## pi: to the left of | |
## | |
## We can generalize this. vertex.label.degree can take a vector as | |
## well as a scalar for its argument. So we write a function to | |
## calculate the right position for a label based on its vertex's location | |
## on the circle. | |
## Get the labels aligned consistently around the edge of the circle | |
## for any n of nodes. | |
## This code borrows bits of ggplot2's polar_coord function | |
## start = offset from 12 o'clock in radians | |
## direction = 1 for clockwise; -1 for anti-clockwise. | |
radian.rescale <- function(x, start=0, direction=1) { | |
c.rotate <- function(x) (x + start) %% (2 * pi) * direction | |
c.rotate(ggplot2::rescale(x, c(0, 2 * pi), range(x))) | |
} | |
### Example | |
## Generate some fake data | |
n <- 15 | |
g <- erdos.renyi.game(n, 0.5) | |
## Obviously labeling in this way this only makes sense for graphs | |
## laid out as a circle to begin with | |
la <- layout.circle(g) | |
lab.locs <- radian.rescale(x=1:n, direction=-1, start=0) | |
plot(g, layout=la, vertex.size=2, vertex.label.dist=1, | |
vertex.label.degree=lab.locs) |
Ditto on the scales::rescale change. Otherwise, the function works great.
Worked well - thanks @lisafeets for making the note about the scales rescale.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hiya, thanks for posting this code! It's just what I needed for my circle graph. I found that I had to change ggplot2::rescale to scales::rescale (line 29) as the latest version of ggplot2 no longer has the rescale function. Besides that this code worked great and my vertex labels look fantastic.