【问题标题】:R ggraph/ggplot2 color legend not displayed properlyR ggraph/ggplot2 颜色图例未正确显示
【发布时间】:2019-11-25 08:00:44
【问题描述】:

我对 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" ) 

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

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

很遗憾,我解决这两个问题的所有尝试均未成功。

【问题讨论】:

    标签: r ggplot2 legend ggraph


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-10-12
      • 1970-01-01
      • 2014-05-18
      • 2016-07-23
      • 2015-11-23
      • 1970-01-01
      • 2021-12-02
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多