#First make sure there are no duplicates in the max_dhw_summary data to join
max_dhw_summary_join <- max_dhw_summary |>
filter(n_dates != 0) |> #get rid of any without data
select(site, sample_date, covariate, value) |>
distinct() |>
group_by(site, sample_date, covariate) |>
summarise(value = mean(value)) |>
ungroup()
#Also remove duplicates in the coral data
coral_data_join <- coral_data |>
distinct() |>
group_by(project, country, site, latitude, longitude, sample_date) |>
summarise(hard_coral_cover = mean(hard_coral_cover)) |>
ungroup()
coral_data_with_covariate <- coral_data_join %>%
left_join(max_dhw_summary_join)
# Determine y-axis max to size the top band appropriately
y_max <- max(coral_data_with_covariate$value, na.rm = TRUE) * 1.05
# Create the scatter plot using plotly
coralDhwScatter <-
plot_ly(data = coral_data_with_covariate,
x = ~hard_coral_cover,
y = ~value,
type = 'scatter',
mode = 'markers',
marker = list(color = "black",
size = 8,
opacity = 0.6),
height = 450,
text = ~paste0(site, ", ", country, "<br>", format(sample_date, "%b %d, %Y")),
hovertemplate = "%{text}<br>Hard coral cover: %{x:.1f}%<br>DHW: %{y:.1f}<extra></extra>") %>%
config(displayModeBar = TRUE,
displaylogo = FALSE,
modeBarButtonsToRemove = c('zoom','pan', 'select', 'zoomIn', 'zoomOut',
'autoScale', 'resetScale', 'lasso2d',
'hoverClosestCartesian',
'hoverCompareCartesian')) %>%
layout(shapes = list(
# Background bands, drawn first so they sit behind the points.
# x0/x1 with xref = "paper" makes each band span the full plot
# width; y0/y1 are in real DHW units.
list(type = "rect",
x0 = 0, x1 = 1, xref = "paper",
y0 = 0, y1 = alert_1,
fillcolor = col_green, opacity = 0.12, line = list(width = 0),
layer = "below"),
list(type = "rect",
x0 = 0, x1 = 1, xref = "paper",
y0 = alert_1, y1 = alert_2,
fillcolor = col_amber, opacity = 0.15, line = list(width = 0),
layer = "below"),
list(type = "rect",
x0 = 0, x1 = 1, xref = "paper",
y0 = alert_2, y1 = y_max,
fillcolor = col_red, opacity = 0.15, line = list(width = 0),
layer = "below"),
# Threshold lines
list(type = "line",
x0 = 0, x1 = 1, xref = "paper", y0 = alert_1, y1 = alert_1,
line = list(color = "black", dash = "dot")),
list(type = "line",
x0 = 0, x1 = 1, xref = "paper", y0 = alert_2, y1 = alert_2,
line = list(color = "black", dash = "dot"))
),
xaxis = list(title = "Hard coral cover (%)",
linecolor = "black",
linewidth = 2,
range = c(0, 100)),
yaxis = list(title = "DHW exposure (past 30 days)",
linecolor = "black",
linewidth = 2,
range = c(0, y_max)),
annotations = list(
list(x = 0, y = 1.15, text = "CORAL COVER VS. HEAT STRESS", showarrow = FALSE,
xref = 'paper', yref = 'paper', xanchor = 'left', yanchor = 'top',
font = list(size = 20)),
list(x = 0, y = 1.08,
text = paste0(nrow(coral_data_with_covariate), " Surveys"),
showarrow = FALSE,
xref = 'paper', yref = 'paper', xanchor = 'left', yanchor = 'top',
font = list(size = 12))
),
margin = list(t = 50, b = 75))
coralDhwScatter