3wF23Xyj
3wF23Xyj

Reputation: 17

Plotting multiple columns against one column in ggplot2 (additional question)

This is a question referring to Plotting multiple columns against one column in ggplot2. Unfortunately I can't comment there so I need to ask it as a new question. Thanks to rnorouzian for asking the question and neilfws for answering.

I'm trying to layer all facets on one scatter plot (with geom_point) with a legend stating the name of the column.

The answer by neilfws contains this code, output was shown in the question:

library(tidyverse)

data <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/vp_cond.csv')

data %>% 
  pivot_longer(cols = 1:12) %>% 
  mutate(name = factor(name, levels = paste0("X", 1:12))) %>% 
  ggplot(aes(x, value)) + 
  geom_line() + 
  facet_wrap(~name) +
  theme_bw()

I tried this and got a good output but without a legend. Where can I specify "name" being used as info in the legend, also using different colors?

data %>% 
  pivot_longer(cols = 1:12) %>% 
  mutate(name = factor(name, levels = paste0("X", 1:12))) %>% 
  ggplot(aes(x, value)) + 
  geom_point() + 
  theme_bw()

Upvotes: 0

Views: 146

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173803

Simply map name to the colour aesthetic. To do this, add colour = name inside aes:

data %>% 
  pivot_longer(cols = 1:12) %>% 
  mutate(name = factor(name, levels = paste0("X", 1:12))) %>% 
  ggplot(aes(x, value, colour = name)) + 
  geom_line() + 
  theme_bw()

enter image description here

Upvotes: 1

Related Questions