首页 > 解决方案 > 如何在 R 中使用 ggplot2 根据大小为节点/geom_point 着色?

问题描述

我正在尝试使用 R 中的 ggnet2 包生成一个图。我创建了一个网络(net.bg)

library(igraph)
library(GGally)
library(network)
library(sna)
library(intergraph)

direction <- c(2,1,3,1,4,1,5,1,3,2,4,2,5,2,4,3,5,3,5,4)
gr <- matrix(direction, nrow = 2)
x1 <- 10.59
x2 <- 15.74
x3 <- 5
x4 <- 18
x5 <- 7

RImp <- data.frame(x1,x2,x3,x4,x5)
nam <- names(RImp)
RImp <- as.numeric(RImp)
Rint <- c(2.96, 1.34, 1.27, 1.1, 2.22, 1.24, 3.11,
          2.52, 0.96, 1.08)

net.bg <- make_graph(gr, 5)

我正在使用 ggnet2 和 ggplot2 来绘制它:

library(RColorBrewer)
library(ggnewscale)
library(ggplot2)


colfunction <- colorRampPalette(c("floralwhite", "firebrick1"))
nodeCol <- colfunction(5)

p   <- ggnet2(net.bg, 
              mode = "circle", 
              size = 0,
              #color = RImp,
              label = nam,
              edge.size = Rint, 
              edge.label = Rint,
              edge.color = "grey") +
  theme(legend.text = element_text(size = 10)) +
  geom_label(aes(label = nam),nudge_y = 0.08) +
  geom_point(aes(fill = RImp), size = RImp, col = nodeCol) +
  scale_fill_continuous(name = "Variable\nImportance",
                        limits=c(0, 20), breaks=seq(0, 20, by= 5),
                        low = "floralwhite" ,high = "firebrick1")
p

ggplot2用来实际绘制节点,而不是ggnet2,因为这允许我添加图例。

上面的代码产生了一个类似这样的图: 网络图

可以看出,节点被着色为渐变,但是,它们以顺时针方式着色......我试图根据节点的大小(或者在这种情况下,包含的值)为节点着色内RImp)。

关于我将如何实现这一目标的任何建议?

标签: rggplot2

解决方案


问题是,点的形状是实心的,并且geom_point使用“nodeCol”作为整个点(或者更确切地说是圆形)的颜色。如果您使用shape = 21,您有机会更改点的轮廓(我在这里使用灰色和填充 - 现在由 正确控制scale_fill_continuous):

  ggnet2(net.bg, 
              mode = "circle", 
              size = 0,
              #color = RImp,
              label = nam,
              edge.size = Rint, 
              edge.label = Rint,
              edge.color = "grey") +
  theme(legend.text = element_text(size = 10)) +
  geom_label(aes(label = nam),nudge_y = 0.08) +
  geom_point(aes(fill = RImp), size = RImp, col = "grey", shape = 21) +
  scale_fill_continuous(name = "Variable\nImportance",
                        limits=c(0, 20), breaks=seq(0, 20, by= 5),
                        low = "floralwhite" ,high = "firebrick1")

如果您在https://ggplot2.tidyverse.org/reference/geom_point.html上向下滚动,您会发现使用不同点形状的示例。


推荐阅读