r - 如何在 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
)。
关于我将如何实现这一目标的任何建议?
解决方案
问题是,点的形状是实心的,并且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上向下滚动,您会发现使用不同点形状的示例。
推荐阅读
- r - 在数据帧的每一行上运行函数,将结果存储在新列中,R
- onlyoffice - 使用 onlyoffice 时,文档(docx、xls 等)物理存储在哪里?
- c++ - 在 C++ 中计算两个日期时间之间的差异
- r - 从 R 对象中提取信息并将其导入模型摘要表
- google-maps - 我如何找到或发送绘制路线谷歌距离矩阵 api 的最短路径?
- apache-iotdb - 如何在次要版本之间升级 Apache IoTDB?
- c - arm-none-eabi-gcc 中的 UINT16_C 定义错误?
- wso2 - 带有 keycloak 的 WSO2 API 管理器使用除 master 以外的其他领域
- python - mpl_toolkits.axisartist:轴的移动标签
- python - 在 jupyter notebook / jupyter lab - python 中请求证书错误