R - 如何修改图例?

标签 r ggplot2 igraph ggraph

我想通过调整列数(例如从一列九行改为三列三行)来修改图中的图例(见下文)。我已经尝试添加 guides(alpha =guide_legend(ncol = 3)) 调整列数。然而,这不起作用(我认为“alpha”不是正确的参数,但我找不到合适的参数)。

示例代码和绘图:

library(dplyr) #required for tibbles
library(igraph) #required for plotting
library(ggraph) #required for plotting
library(Cairo) #required for anti-aliasing

nodes = LETTERS[1:10] #define nodes
nc = expand.grid(nodes,nodes) #connect all nodes with edges
nc = nc[-which(nc[,1] == nc[,2]),] #remove node connections to themselves 
set.seed(666)
nc = cbind(nc, runif(nrow(nc),0,1)) #add random weights
ne = tibble(from = nc[,1], to = nc[,2], wt = as.numeric(nc[,3])) 

g = graph_from_data_frame(ne) #create graph from nodes and edges
CairoWin() #open window with anti-aliased plot
ggraph(g, layout = "circle") + 
  geom_edge_link(aes(alpha = wt), edge_width = 1) + #add edges with weight
  geom_node_point(size = 10, fill = "white", color = "black", shape = 21, stroke = 1.5) + 
  geom_node_text(aes(label = name)) +
  scale_edge_alpha_continuous(name = "Weight", seq(0,1,0.1)) +
  theme_void() 

enter image description here

非常感谢您的帮助!

最佳答案

这是因为边缘的 alpha 内部称为 edge_alpha,而不是 alpha,就像 aes() 让您相信的那样。因此,您可以使用 scale_edge_alpha_continuous() 来定义图例:

library(dplyr) #required for tibbles
library(igraph) #required for plotting
library(ggraph) #required for plotting

nodes = LETTERS[1:10] #define nodes
nc = expand.grid(nodes,nodes) #connect all nodes with edges
nc = nc[-which(nc[,1] == nc[,2]),] #remove node connections to themselves 
set.seed(666)
nc = cbind(nc, runif(nrow(nc),0,1)) #add random weights
ne = tibble(from = nc[,1], to = nc[,2], wt = as.numeric(nc[,3])) 

g = graph_from_data_frame(ne) #create graph from nodes and edges

p <- ggraph(g, layout = "circle") + 
  geom_edge_link(aes(alpha = wt), edge_width = 1) + #add edges with weight
  geom_node_point(size = 10, fill = "white", color = "black", shape = 21, stroke = 1.5) + 
  geom_node_text(aes(label = name)) +
  theme_void() 

p + scale_edge_alpha_continuous(name = "Weight", seq(0,1,0.1),
                                guide = guide_legend(nrow = 3))

或者,如果您命名了正确的美学,您也可以使用 guides() 函数指定它。

p + scale_edge_alpha_continuous(name = "Weight", seq(0,1,0.1)) +
  guides(edge_alpha = guide_legend(nrow = 3))

reprex package 于 2022 年 1 月 21 日创建(v2.0.1)

关于R - 如何修改图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70799664/

相关文章:

python - 使用R的rPython来运行python的rpy2

r - 如何使用 ggplots 和 map 添加自定义图例

r - R 中的 igraph : Directed graphs (with arrows) causes vertex color transparency

r - 具有 2 个 y 轴(辅助 y 轴)的 2 个 ts 对象(时间序列)的 ggplot

r - 将决策边界拟合到 R 中的逻辑回归模型

python-igraph 从文件创建图形

r - 编写图形并保留顶点名称

r - PCA - 主要成分是如何映射的?

r - 在 Y 列数据的条件下转置 X 列数据

r - R是否存在现有的ANTLR或IRONY语法?