Search code examples
rr-plotly

Assign color to histogram in R


I have a dataframe that looks like :

Global.df.Selected <- structure(list(Year.of.Issuance = c(
  2014L, 2017L, 2017L, 2017L,
  2016L, 2017L
), Region.of.Risk = c(
  "North America", "Europe",
  "Europe", "Europe", "North America", "North America"
), color = c(
  "#2874A6",
  "#5DADE2", "#5DADE2", "#5DADE2", "#2874A6", "#2874A6"
)), row.names = c(
  NA,
  -6L
), class = "data.frame")

I would like to create an histogram and assign the colors (which are based on the region of risk already). I have done the following :

plotly::plot_ly(Global.df, x = ~Year.of.Issuance, color = ~Region.of.Risk) %>%
  plotly::add_histogram() %>%
  plotly::layout(yaxis = list(title="Y axis label"),
         legend = list(
           orientation = "h",
           # show entries horizontally
           xanchor = "center",
           # use center of legend as anchor
           x = 0.5,
           y = -0.15
         ))

How can I get plotly to precisely use the colors which are on Global.df.Selected$color vector

enter image description here


Solution

  • One approach to achieve this is to make use of a named vector of colors which could be passed to ploly via argument colors. Try this:

    library(plotly)
    
    # Make named color vector
    colors <- Global.df.Selected %>%
      select(Region.of.Risk, color) %>%
      distinct() %>%
      tibble::deframe()
    
    plotly::plot_ly(Global.df.Selected, x = ~Year.of.Issuance, color = ~Region.of.Risk, colors = colors) %>%
      plotly::add_histogram() %>%
      plotly::layout(
        yaxis = list(title = "Y axis label"),
        legend = list(
          orientation = "h",
          # show entries horizontally
          xanchor = "center",
          # use center of legend as anchor
          x = 0.5,
          y = -0.15
        )
      )
    

    enter image description here