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
953 views
in Technique[技术] by (71.8m points)

r - Plotly's fillcolor defaults to half-transparency, want no-transparency

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: enter image description here

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/.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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:

enter image description here


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

...