如何在plotly中制作用户定义/显式色阶和图例?

时间:2018-02-10 16:39:01

标签: r colors plotly legend

我有按月分类的数据集。但是,当我绘制每个子集的图形时,图例的颜色比例和范围都是不同的。如何明确定义它,以便它在所有子集中保持一致?

因此,在下面的示例中,我希望未经过滤的数据集和已过滤的数据集的颜色比例和图例范围相同。

github link to dataset

#original dataset. I want to construct the legend with this
weather <- read.csv("weather2_rmse.csv") %>% 
  mutate(date_of_forecast = as.Date(date_of_forecast))

#filtered. I want to construct the points with this
data <- filter(weather, date_of_forecast == "2015-02-01")

weather_map <- function(data) {

  # change default color scale title
  m <- list(colorbar = list(title = ""))

  # geo styling
  g <- list(
    scope = 'north america',
    showland = TRUE,
    landcolor = toRGB("grey83"),
    subunitcolor = toRGB("white"),
    countrycolor = toRGB("white"),
    showlakes = TRUE,
    lakecolor = toRGB("white"),
    showsubunits = TRUE,
    showcountries = TRUE,
    resolution = 50,
    projection = list(
      type = 'conic conformal',
      rotation = list(lon = -100)
    ),
    lonaxis = list(
      showgrid = TRUE,
      gridwidth = 0.5,
      range = c(-140, -55),
      dtick = 5
    ),
    lataxis = list(
      showgrid = TRUE,
      gridwidth = 0.5,
      range = c(20, 60),
      dtick = 5
    )
  )

  #the plotly part
  p <- plot_geo(data, lat = ~latitude, lon = ~longitude, color = ~rmse) %>%
    add_markers(
      text = ~paste(data$rmse, "RMSE"), hoverinfo = "text"
    ) %>%
    layout(title = 'Average RMSE of MaxTemp Forecasts by Month<br>xxxxxxxxxx', geo = g)
  p
}

1 个答案:

答案 0 :(得分:0)

例如,这样:定义比例,例如

scl = list(c(0, "rgb(0, 0, 255)"), list(1, "rgb(0, 255, 0)"))

(你也可以添加更多的值,这是基于分位数AFAIK。所以这样设置

scl = list(c(0, "rgb(0, 0, 255)"), list(0.1, "rgb(0, 0, 255)"),
           c(0.1, "rgb(0, 255, 0)"), list(1, "rgb(0, 255, 0)"))

将使前10%的值为蓝色,其余为绿色。

然后,修改您的情节调用,例如像这样:

  p <- plot_geo(data) %>%
    add_markers(y = ~latitude, x = ~longitude,
                mode = "markers", type = "scatter", 
                marker = list(color = ~rmse,
                              colorscale = scl,
                              cauto = FALSE,
                              colorbar = list(title=""),
                              cmax = 15,
                              cmin = 0)) %>%
    layout(title = 'Average RMSE of MaxTemp Forecasts by Month<br>xxxxxxxxxx', geo = g)
  p

通过使用cmaxcmin设置确切的限制,您应该在子图上具有相同的比例