问题描述
我正在使用 ggnet
和 ggplot
创建网络样式图.目前,我只是使用 geom_label
的 nudge_y
参数来放置标签.但是我想知道是否可以放置标签,使它们始终位于圆的外部(我的网络始终是圆形的).一个玩具示例如下所示.
I am creating a network style plot using ggnet
and ggplot
. At the moment im just using geom_label
's nudge_y
argument to position the labels. But I was wondering if it's possible to position the labels so they are always on the outside of the circle (my network is always circular). A toy example is shown below.
library(ggplot2)
library(igraph)
library(GGally) # contains ggnet2
nam <- c("A", "B", "C", "D", "E") # Node name
g <- sample_pa(5, m = 5) # generate graph with x nodes
g <- igraph::as_data_frame(g) # create df
g <- rbind(g$to,g$from) # create matrix
net.bg <- make_graph(g, 5, directed = FALSE) #make graph
E(net.bg)$weight <- sample(1:3, 5,replace=T)
V(net.bg)$size <- sample(1:5, 5,replace=T)
p <- ggnet2(net.bg,
mode = "circle",
size = V(net.bg)$size,
node.color = "red",
edge.size = E(net.bg)$weight,
edge.alpha = 0.5,
edge.color = "blue") +
theme(legend.text = element_text(size = 10)) +
geom_label(aes(label = nam),nudge_y = 0.05)
p
上面的代码产生如下内容:
The above code produces something like this:
可以看出,所有标签都在y方向上微移.但是我希望做这样的事情(我在PowerPoint中制作):
As can be seen, the labels are all nudged in the y direction. But I was hoping to make something like this (which I made in powerpoint):
有可能做这样的事情吗?
Is it possible to do such a thing?
推荐答案
这是可能的,尽管不是特别容易或便携.对象 p
是ggplot对象,因此包含在坐标,几何,映射,数据等方面构建图所需的所有信息.
It is possible, though not particularly easy or portable. The object p
is a ggplot object, so contains all the information required to build the plot in terms of co-ordinates, geoms, mapping, data, etc.
这意味着您可以直接更改 labels
图层,以便其x,y坐标比其先前值小一倍.因此,您可以这样做:
This means you can directly change the labels
layer so that its x, y co-ordinates are a small multiple above their previous values. So you could do:
geoms <- sapply(p$layers, function(x) class(x$geom)[1])
segments <- p$layers[[which(geoms == "GeomSegment")]]
labels <- p$layers[[which(geoms == "GeomLabel")]]
segments$data <- segments$data - 0.5
p$data$x <- p$data$x - 0.5
p$data$y <- p$data$y - 0.5
labels$position$y <- 0
labels$data <- p$data
labels$data$x <- labels$data$x * 1.1
labels$data$y <- labels$data$y * 1.1
p$scales$scales <- lapply(p$scales$scales, function(x) {
if(class(x)[1] == "ScaleContinuousPosition") ScaleContinuousPosition else x })
p <- p + theme(axis.text = element_blank())
p
这篇关于使用ggplot将geom_label放置在网络外部吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!