问题
I am using visNetwork to visualize a graph, but I need to introduce a legend based on the edge color. edge color is dependent on an edge attribute and its dynamic in nature. I tried to do with visGroups/visLegend, but got multiple errors. PFB reproducible example.
library(igraph)
library(visNetwork)
gg <- graph.atlas(711)
V(gg)$name=1:7
gg=set_edge_attr(gg,"Department",E(gg)[1:10],c("A","B","C","A","E","C","G","B","C","A"))
E(gg)$label=E(gg)$Department
F2 <- colorRampPalette(c("red", "blue","orange","violet","cyan"), bias = length(unique(E(gg)$Department)), space = "rgb", interpolate = "linear")
colCodes <- F2(length(unique(E(gg)$Department)))
edges_col <- sapply(E(gg)$Department,function(x) colCodes[which(sort(unique(E(gg)$Department)) == x)])
E(gg)$color <-edges_col
datatest = toVisNetworkData(gg)
visNetwork(datatest$nodes,datatest$edges) %>% visIgraphLayout(layout="layout_in_circle")
I need legends as Red - A , Blue - C etc.
Kindly help.
回答1:
visLegend
is first based on nodes groups, but you can also set nodes and/or edges legend manually. (?visLegend
)
For you for example :
# data.frame from edges legend
ledges <- data.frame(color = unique(edges_col),
label = unique(names(edges_col)))
visNetwork(datatest$nodes,datatest$edges) %>% visIgraphLayout(layout="layout_in_circle") %>%
visLegend(useGroups = F, addEdges = ledges)
来源:https://stackoverflow.com/questions/38602251/adding-a-legend-in-visnetwork-for-edge-color