R/plot_kols.R

Defines functions plot_kols

Documented in plot_kols

#' Plot a KOL team in a network
#'
#' @param KOL a KOL object generated by \code{pick_kols()}
#' @param team numeric: number of team in \code{KOL} to plot
#' @param kol color to mark KOLs
#' @param reachable color to mark nodes reachable by KOLs
#' @param attribute boolean: if a node attribute was used to measure KOL team diversity, should nodes be colored accordingly
#' @param ... arguments passed to \code{igraph} plot function
#'
#' @returns an igraph plot
#' @export
#'
#' @examples
#' network <- igraph::sample_smallworld(1,26,2,.2)  #An example network
#' teams <- pick_kols(network, m = 2)  #Find KOL teams
#' plot_kols(teams,
#'           vertex.label = NA,
#'           vertex.frame.width = 3)
plot_kols <- function(KOL,
                      team = 1,
                      kol = "red",
                      reachable = "green",
                      attribute = TRUE,
                      ...) {

  #### Parameter Checks ####
  if (!methods::is(KOL,"KOL")) {stop("`KOL` must be a KOL object generated by the pick_kols() function")}
  if (!is.numeric(team)) {stop(paste0("`team` must be an integer between 1 and ", nrow(KOL)))}
  if (team%%1!=0 | team<1 | team>length(KOL$teams)) {stop(paste0("`team` must be an integer between 1 and ", igraph::gorder(KOL$network)))}

  #### Prepare igraph object ####
  network <- KOL$network
  igraph::V(network)$frame <- NA
  igraph::V(network)$color <- "black"
  if (!is.null(KOL$attribute)) {if (attribute) {igraph::V(network)$color <- igraph::vertex_attr(network,KOL$attribute)}}

  #### Identify and mark KOL team members ####
  kols <- unlist(strsplit(KOL$teams$team[team], split = ", "))  #Members of selected KOL team
  if (!is.null(igraph::V(network)$name)) {kols <- which(igraph::V(network)$name %in% kols)} else {kols <- as.numeric(kols)}  #Indices of KOLs
  network <- igraph::set_vertex_attr(network, "frame", kols, kol)  #Give KOL nodes a red frame

  #### Identify nodes covered by KOLs ####
  if (KOL$goal=="diffusion") {
    dist <- igraph::distances(network)  #Get distances
    if (length(kols)>1) {covered <- which(apply(dist[kols,],2,min)<=KOL$m)}  #Indices of nodes that are covered
    if (length(kols)==1) {covered <- which(dist[kols,]<=KOL$m)}
  }

  if (KOL$goal=="adoption") {
    M <- igraph::as_adjacency_matrix(network, sparse = FALSE)  #Get adjacency matrix
    covered <- which(colSums(M[kols,])>=KOL$m )  #Indices of nodes that are covered
  }

  #### Mark nodes covered by KOLs ####
  covered <- covered[which(!(covered %in% kols))]  #Remove KOLs from list of covered nodes
  network <- igraph::set_vertex_attr(network, "frame", covered, reachable)  #Give covered nodes a green frame

  #### Plot the network ####
  plot(network, vertex.frame.color = igraph::V(network)$frame, ...)
}

Try the KOLaide package in your browser

Any scripts or data that you put into this service are public.

KOLaide documentation built on June 8, 2025, 1:16 p.m.