Reputation: 31
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
Reputation: 78907
row_number()
pivot_longer
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()
data:
df <- tribble(
~WindSpeed9am, ~WindSpeed3pm,
6, 20,
4, 17,
30, 6 )
Upvotes: 1
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
df <- read.table(text = "WindSpeed9am WindSpeed3pm
6 20
4 17
30 6 ", header = TRUE)
Upvotes: 1
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")
Upvotes: 0