Skip to content

Support factor variables for x and/or y when numeric variable is used to set color #2404

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Added test case
  • Loading branch information
BeppoBrem committed Dec 7, 2024
commit 24f81d0784b62a8b1ceffe80491309849cf0366f
4 changes: 3 additions & 1 deletion R/plotly_build.R
Original file line number Diff line number Diff line change
Expand Up @@ -890,7 +890,9 @@ map_color <- function(traces, stroke = FALSE, title = "", colorway, na.color = "
# 3D needs a z property
if ("scatter3d" %in% types) {
colorBarTrace$type <- "scatter3d"
colorBarTrace$z <- range(unlist(lapply(traces, "[[", "z")), na.rm = TRUE)
zValues <- unlist(lapply(traces, "[[", "x"))
zValues <- if (is.numeric(zValues)) range(zValues, na.rm = TRUE) else zValues
colorBarTrace$z <- zValues
}
if (length(type <- intersect(c("scattergeo", "scattermapbox"), types))) {
colorBarTrace$type <- type
Expand Down
7 changes: 7 additions & 0 deletions tests/testthat/test-plotly-color.R
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ test_that("Mapping a factor variable to color works", {
expect_equivalent(length(cols), 3)
})

test_that("A scatterplot with a factor variable and discrete color works", {
d <- palmerpenguins::penguins
p <- plot_ly(d, x = ~bill_length_mm, y = ~sex, color = ~bill_depth_mm,
type = 'scatter', mode = 'markers')
l <- expect_traces(p, 2, "scatterplot-factor-continous-color")
})

test_that("Custom RColorBrewer pallette works for factor variable", {
d <- palmerpenguins::penguins %>%
filter(!is.na(bill_length_mm))
Expand Down