【问题标题】:How to colour nodes/geom_point a gradient based on size using ggplot2 in R?如何使用 R 中的 ggplot2 根据大小为节点/geom_point 着色?
【发布时间】:2020-02-20 01:19:06
【问题描述】:

我正在尝试使用 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 中包含的值)。

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    问题是,点的形状是实心的,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,您会发现使用不同点形状的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多