R ggraph/ggplot2 颜色图例显示不正确

标签 r ggplot2 legend ggraph

我是 ggraph 的新手,为了让图例正确显示节点的颜色,我费了一番功夫。 我有以下示例数据集:

nodes <- data.frame( ID =  c( 2, 3, 4, 5, 6, 7 ),  
                     cl = c( "A", "B", "A", "A", "C", "B" ), 
                     ty = c( 1, 1, 0, 0, 0, 1 ), 
                     assets = c( 20000000, 10000, 500000, 10000, 150, 50 )
                    )


edges <- data.frame( from = c( 2, 5, 4, 6, 7, 4, 3 ), 
                     to = c( 3, 4, 3, 5, 5, 3, 2 ), 
                     we = c( 1, 1, 3, 2, 1, 1, 3 ), 
                     pa = c( 0, 0, 1, 0, 1, 0, 0 ))

根据这些数据,我尝试绘制图表:

library( 'tidygraph' )
library( 'igraph' )
library( 'ggraph' )

graph <- graph_from_data_frame( edges, vertices = nodes, directed = TRUE ) %>% as_tbl_graph()


ggraph( graph, layout = 'fr' ) + 
  # Create edge layer
    geom_edge_link0( aes( width = we, color = factor( pa )), 
                          arrow = arrow( angle = 10, length = unit( 0.15, "inches" ),
                                         ends = "last", type = "closed" )) +
    scale_edge_width( range = c( 0.2, 2.2 )) +
    scale_edge_color_grey( start = 0.4, end = 0.8 ) +
  # Create node layer
    geom_node_point( aes( shape = factor( ty ), fill = cl, size = log( assets ))) +
  # Title and legend
    labs( edge_width = "Power", edge_color = "Ownertype" ) +
    ggtitle( "Title" ) +
    theme( legend.key = element_rect( fill = "white", colour = "black" ), 
    legend.title = element_text(face = "bold" )) +
    scale_size_continuous( name = "Assets", range = c( 3, 6 ), breaks = c( 5, 10, 15 )) +
    scale_shape_manual( name = "Same branch", values = c( 21, 23 ), labels = c( "no", "yes" )) +
    scale_fill_brewer( name = "Sector", palette = "Dark2" ) 

Adding image - This is the result

我对“部门”标题下的图例有两个问题:

  1. 不显示颜色键,它们都是黑色的。每当我让节点的颜色和形状都发生变化时,就会发生这种情况。
  2. 颜色键太小,很难区分颜色(一旦有)。

不幸的是,我为解决这两个问题所做的所有尝试都没有成功。

最佳答案

默认情况下,点的图例指南不使用支持填充颜色的形状。您需要为指南设置这样的形状:

+ guides(fill = guide_legend(override.aes = list(size = 5, shape = 21)))

resulting plot showing fill colors in the legend correctly

关于R ggraph/ggplot2 颜色图例显示不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59027381/

相关文章:

r - 在 R doParallel 'foreach' 中找不到函数 - { : task 1 failed - "could not find function "raster""中出现错误

r - 有没有办法将 R 对象传输到 Linux 上的单独 R session ?

r - bquote 在 ggplot2 2.1 版的 facet_grid 标签中不起作用

python - matplotlib 图例中的下划线文本

r - 如何从年、月和日的整数值初始化 R 中的日期

r - data.frames 列表按行快速矢量化合并

r - 在 grid.arrange 中绘制图例、间隔良好的通用 y 轴和主标题

r - 在具有不同 x-y 轴的面中绘制多个矩阵

graph - Stata 图表中没有水平线且没有图例边框

python - 图例中的错误栏- Pandas 栏图