Skip to contents

This function allows you to dynamically position the legend of a networkD3 plot. The legend is positioned as a percentage of the x and y coordinates relative to the size of the plot. In addition, you can choose whether the legend items are arranged vertically (default) or horizontally.

Usage

move_networkd3_legend(
  netd3,
  x_pos = 0.85,
  y_pos = 0.5,
  legend_spacing = 25,
  align = "left",
  orientation = "vertical"
)

Arguments

netd3

An object of class networkD3 (specifically a forceNetwork).

x_pos

numeric. A numeric value between 0 and 1 that defines the horizontal position of the legend. 0 is the far left, and 1 is the far right of the plot. Default is 0.85.

y_pos

numeric. A numeric value between 0 and 1 that defines the vertical position of the legend. 0 is the top, and 1 is the bottom of the plot. Default is 0.5 (centered).

legend_spacing

numeric. A numeric value controlling the spacing between legend items (pixels). Default is 25 px.

align

character. A character string controlling the horizontal alignment of the legend items. Possible values are "left", "center", and "right". Default is "left".

orientation

character. A character string for the legend layout. Either "vertical" (default) or "horizontal".

Value

A networkD3 object with the legend positioned according to the specified options.

Examples

library(networkD3)
nodes <- data.frame(name = c("A", "B", "C", "D", "E", "F"))
links <- data.frame(source = c(0, 1, 2, 3, 4),
                    target = c(1, 2, 3, 4, 5),
                    value = c(1, 1, 1, 1, 1))

netd3 <- forceNetwork(Links = links, Nodes = nodes,
                      Source = "source", Target = "target",
                      Value = "value", NodeID = "name",
                      legend = TRUE, Group = "name")

# Vertical legend (default)
netd3_v <- move_networkd3_legend(netd3, x_pos = 0.2, y_pos = 0.3, legend_spacing = 35)

# Horizontal legend
netd3_h <- move_networkd3_legend(netd3, x_pos = 0.4, y_pos = 1, orientation = "horizontal")