本文介绍了Plotly的fillcolor默认为半透明,要不透明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Plotly在R中构建地图.我将在回复本文中分享构建数据框所需的代码.这是我用来绘制图表的代码:

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:

我的问题很容易理解,但是我找不到解决此问题的方法.我希望每个不同县的填充色与该县的边界线具有相同的蓝色阴影.在plotly的文档中,它指出了fillcolor:

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(颜色)
设置填充颜色.默认为线条颜色,标记颜色或标记线条颜色的半透明变体(以可用者为准).

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.

问题就在这里……我不想要线色的半透明变体,我想要实际的线色!我尝试过将许多不同的值传递给fillcolor参数,但是没有运气.任何帮助,将不胜感激!

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!

谢谢!

编辑-佛罗里达数据帧上的输出非常大,超过了RStudio控制台的打印输出最大值.不过,这里有一些类似的,可复制的示例- https://plot.ly/r/county- level-choropleth/.

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

推荐答案

我对图进行了深入研究,但没有找到直接的解决方案.但是,我们可以使用htmlwidgets包中的函数prependContent来调整渲染图.这是一个简单的示例:

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)

我们基本上将一些CSS注入到小部件容器中,并使用!important来确保样式不会被覆盖.

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

在这里您可以看到alpha = 00.250.751的结果:

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

这篇关于Plotly的fillcolor默认为半透明,要不透明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 16:43