Search code examples
rggplot2legenddensity-plot

Changing the Legend Title in a `ggpointdensity` Density Scatterplot


I have the following data and the following graph.

df <- data.frame(col1 = rnorm(1000, 0, 0.05), col2 = rnorm(1000, 0, 0.05))
ggplot(data = df, mapping = aes(x = col1, y = col2)) +
  geom_pointdensity() +
  scale_color_viridis()

Plot

To make a publication-quality figure, I'd like to change the legend title from "n_neighbors" to "Point Density". I've tried a couple things, but neither of them worked.

ggplot(data = df, mapping = aes(x = col1, y = col2)) +
  geom_pointdensity() +
  scale_color_viridis() +
  labs(fill = "Point Density")
ggplot(data = df, mapping = aes(x = col1, y = col2)) +
  geom_pointdensity() +
  scale_color_viridis() +
  guides(fill = guide_legend(title = "Point Density"))

Is there a way to make this change?


Solution

  • You can change the legend title using the name argument in the scale_color_viridis() function:

    library(viridis)
    library(ggpointdensity)
    library(ggplot2)
    df <- data.frame(col1 = rnorm(1000, 0, 0.05), col2 = rnorm(1000, 0, 0.05))
    ggplot(data = df, mapping = aes(x = col1, y = col2)) +
      geom_pointdensity() +
      scale_color_viridis(name = "Point Density")
    

    enter image description here

    Alternatively, using the color argument in labs():

    ggplot(data = df, mapping = aes(x = col1, y = col2)) +
      geom_pointdensity() +
      scale_color_viridis() +
      labs(color = "Point Density")
    

    or in guides():

    ggplot(data = df, mapping = aes(x = col1, y = col2)) +
      geom_pointdensity() +
      scale_color_viridis() +
      guides(color = guide_legend(title = "Point Density"))
    

    The point color comes from the color argument, not fill which is why your original code didn't work.