R - 如何修改图例?

R - How to modify the legend?

我想通过调整列数(例如,从一列九行改为三列三行)来修改我的图中的图例(见下文)。我已经尝试添加 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() 

非常感谢您的帮助!

这是因为边缘的 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 (v2.0.1)

创建于 2022-01-21