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

时间:2019-11-25 08:00:44

标签: 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. 颜色键太小,因此很难区分颜色(一旦它们在那里)。

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

1 个答案:

答案 0 :(得分:2)

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

AForge.Video.DirectShow

resulting plot showing fill colors in the legend correctly