user15330212
user15330212

Reputation: 31

R-ggplot2 geom_line() in R

WindSpeed9am    WindSpeed3pm
6               20
4               17
30              6 

New to R language. I want to use geom_line for to compare both of these attributes. How do I do it?

Upvotes: 0

Views: 831

Answers (3)

TarJae
TarJae

Reputation: 78907

  1. Add id column for x axis with row_number()
  2. bring data in long format with pivot_longer
  3. use ggplot colour and group for geom_line
library(tidyverse)
df1 <- df %>% 
  mutate(id = row_number()) %>% 
  pivot_longer(
    cols = -id
  )
ggplot(df1, aes(factor(id), value, colour=name, group=name)) +
  geom_point() +
  geom_line()

enter image description here

data:

df <- tribble(
~WindSpeed9am,    ~WindSpeed3pm,
6,            20,
4,               17,
30,              6 )

Upvotes: 1

JBGruber
JBGruber

Reputation: 12410

To use geom_line, you need at least two variables (for the x and y-axis). From context, I added a variable day:

library(tidyverse)

df %>% 
  mutate(day = row_number()) %>%                     # add second variable for x-axis
  pivot_longer(WindSpeed9am:WindSpeed3pm) %>%        # turn into a tidy/long format which ggplot expects
  ggplot(aes(x = day, y = value, colour = name)) +   # start the plot and set aesthetics
  geom_line()                                        # add lines

Created on 2021-05-15 by the reprex package (v2.0.0)

This is a rather basic question, so as an extra to the specific answer I suggest you learn more about ggplot2 from this book

data

df <- read.table(text = "WindSpeed9am    WindSpeed3pm
6               20
4               17
30              6 ", header = TRUE)

Upvotes: 1

Elia
Elia

Reputation: 2584

Something like this?

WindSpeed9am <- c(6,4,30) 
WindSpeed3pm <- c(20,17,6)
df <- data.frame(WindSpeed9am,WindSpeed3pm)

library(ggplot2)
ggplot(df)+
  geom_line(aes(x=1:3,y=WindSpeed3pm),col="red")+
  geom_line(aes(x=1:3,y=WindSpeed9am),col="blue")

enter image description here

Upvotes: 0

Related Questions