stixiris
stixiris

Reputation: 1

How to combine legends in ggplot2

I'm a beginner learner with R. I've been attempting to combine legends for so long and just can't seem to do it.

Data works fine and is accurate and plotted properly. Except colour and shape aren't combined in one legend but in separate legends.

Here's my code:


ggp1 <- ggplot(data, aes(x = Year)) +
  geom_point(aes(y = Temperature, colour = "Africa", shape = "Africa")) +  
  geom_point(aes(y = y2, colour = "Asia", shape = "Asia")) +
  geom_point(aes(y = y3, colour = "Europe", shape = "Europe")) + 
  geom_point(aes(y = y4, colour = "Australia", shape = "Australia"))

Edit: Here's the data:

data <- data.frame(Year = df1$Year,
               Temperature = df1$Temperature.Africa,
               y2 = df1$Temperature.Asia,
               y3 = df1$Temperature.Europe,
               y4 = df1$Temperature.Australia)
          

This is the output of the code

Please help before I go crazy.

Upvotes: 0

Views: 163

Answers (1)

stefan
stefan

Reputation: 123783

You could achieve your desired result by assigning the same name to the color and shape legends or by removing both as I do in my code below using labs.

Using a minimal reproducible example based on the gapminder dataset:

library(gapminder)
library(tidyverse)

# Create example data
data <- gapminder |> 
  select(Year = year, continent, value = lifeExp) |> 
  group_by(Year, continent) |> 
  summarise(value = mean(value), .groups = "drop") |> 
  pivot_wider(names_from = continent, values_from = value) |> 
  select(Year, Temperature = 2, y2 = 3, y3 = 4, y4 = 5)
  
ggplot(data, aes(x = Year)) +
  geom_point(aes(y = Temperature, colour = "Africa", shape = "Africa")) +  
  geom_point(aes(y = y2, colour = "Asia", shape = "Asia")) +
  geom_point(aes(y = y3, colour = "Europe", shape = "Europe")) + 
  geom_point(aes(y = y4, colour = "Australia", shape = "Australia")) +
  labs(color = NULL, shape = NULL)

Upvotes: 1

Related Questions