Plotly's fillcolor defaults to half-transparen

2020-04-17 06:24发布

问题:

I am trying to build a map in R using plotly. I will share the code required to build the dataframe in a reply to this post. Here is the code I am using to plot the chart:

florida %>%
  group_by(group) %>%
  plot_ly(x = ~long, y = ~lat, 
          color = ~color_vals, colors = 'Blues') %>%
  add_polygons(line = list(width = 2),
               # fillcolor = 'WHAT GOES HERE',
               opacity = 1, showlegend = FALSE)

and here is the output I am getting:

My issue is simple to understand, but I cannot find a way to fix this. I'd like the fillcolor for each of the different counties to be the same shade of blue as the boundary lines for that county. In plotly's documentation, it states for fillcolor:

fillcolor (color)
Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available.

And herein lies the problem... I don't want a half-transparent variant of the line color, I want the actual line color! I've tried passing many different values to the fillcolor parameter, but have had no luck. Any help with this would be super appreciated!

Thanks!

EDIT - the dput on the florida dataframe is very very large, exceeding the RStudio console's print output max. Some similar, reproducible examples are here though - https://plot.ly/r/county-level-choropleth/.

回答1:

I digged a bit into plotly and did not find a direct solution to this. However, we can use the function prependContent from the htmlwidgets package to tweak the rendered plot. Here is a simple example:

library(plotly)
library(dplyr)
library(htmlwidgets)
library(htmltools)

# define utility function to adjust fill-opacity using css
fillOpacity <- function(., alpha = 0.5) {
  css <- sprintf("<style> .js-fill { fill-opacity: %s !important; } </style>", alpha)
  prependContent(., HTML(css))
}


ggplot2::map_data("world") %>%
  group_by(group) %>%
  plot_ly(x = ~long, y = ~lat) %>%
  add_polygons() %>%
  fillOpacity(alpha = 1)

We basically inject some CSS into the widget container and use !important in order to make sure the styles wont be overwritten.

Here you can see the results for alpha = 0, 0.25, 0.75 and 1:



回答2:

Without modifying anything in Plotly, I found that you can add

alpha = 1

to add_trace/add_polygons to change it to completely opaque. So where you have your fillcolor comment, you can drop in

alpha = 

then 0-1, completely transparent to completely opaque.



标签: r maps plotly