Skip to content

messed up bin order when using guide_coloursteps with geom_contour_filled #6093

Closed
@mluerig

Description

@mluerig

When using geom_contour_filled, I prefer guide_colorsteps over the discrete legend type. However, in some cases the order of my bins will be messed up if I use the former.

image

library(ggplot2)

# Generate mock data
set.seed(42)
x <- seq(-10, 10, length.out = 100)
y <- seq(-10, 10, length.out = 100)
z <- outer(x, y, function(x, y) 450 * exp(-0.1 * (x^2 + y^2)))

# Create a data frame for ggplot
data <- expand.grid(x = x, y = y)
data$z <- as.vector(z)

# Create the ggplot with geom_contour_filled
p = ggplot(data, aes(x = x, y = y, z = z)) +
  geom_contour_filled(breaks = seq(0, 450, by = 50)) +
  scale_fill_viridis_d() +
  labs(title = "Filled Contour Plot", x = "X-axis", y = "Y-axis", fill = "Levels") +
  theme_minimal() 

## as expected
p 

## messed up order (100 on top instead of between 50 and 150)
p + guides(fill=guide_coloursteps(order=1, 
                                keywidth = unit(0.5, "cm"),
                                keyheight = unit(4, "cm"),
                                title.position = "top",
                                show.limits = T))

I am not sure when exactly, but it seems to change with the breaks argument in the geom.

## works
ggplot(data, aes(x = x, y = y, z = z)) +
  geom_contour_filled(breaks = seq(0, 450, by = 100)) +
  scale_fill_viridis_d() +
  labs(title = "Filled Contour Plot", x = "X-axis", y = "Y-axis", fill = "Levels") +
  theme_minimal() +
  guides(fill=guide_coloursteps(order=1, 
                                  keywidth = unit(0.5, "cm"),
                                  keyheight = unit(4, "cm"),
                                  title.position = "top",
                                  show.limits = T))

## doesn't work
ggplot(data, aes(x = x, y = y, z = z)) +
  geom_contour_filled(breaks = seq(0, 450, by = 25)) +
  scale_fill_viridis_d() +
  labs(title = "Filled Contour Plot", x = "X-axis", y = "Y-axis", fill = "Levels") +
  theme_minimal() +
  guides(fill=guide_coloursteps(order=1, 
                                keywidth = unit(0.5, "cm"),
                                keyheight = unit(4, "cm"),
                                title.position = "top",
                                show.limits = T))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions