Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

r - Change background color of networkD3 plot

Say I make a networkD3 plot - using the minimal example in the package

#
library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
            Source = "source", Target = "target",
            Value = "value", NodeID = "name",
            Group = "group", opacity = 0.8)

If I open this in the browser, I can use developer tools to change the background color of body to e.g. background-color: #DAE3F9;"

Is there a way to automatically define background color of a plot (From default white) to another color, without opening in the browser ? Basically, can we add CSS directly to the code like we can add JS functions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If possible, we can use some help from htmltools in a couple ways.

library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
             Source = "source", Target = "target",
             Value = "value", NodeID = "name",
             Group = "group", opacity = 0.8)

library(htmltools)

# don't like using the !important modifier
#  but without script not sure there is another way
#  to override the default white background
browsable(
  tagList(
    tags$head(
      tags$style('body{background-color: #DAE3F9 !important}')
    ),
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8)
  )
)

# if you want to limit the background-color to
#  the htmlwidget, we could wrap in tags$div
browsable(
  tags$div(
    style = "background-color:#DAE3F9;",
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8)
  )
)

# if you are ok with script then we
#  we could do something like this
browsable(
  tagList(
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8),
    tags$script(
'
document.body.style.backgroundColor = "#DAE3F9"
'      
    )
  )
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...