0
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?

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Really appreciate for your time and help! Learned something now!
You're welcome! You can upvote and/or accept the answer to show it helped you ;)
1
  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 )

1 Comment

Thanks! Really appreciate for your answer! It works!
0

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

1 Comment

Thanks! Appreciate for your help! This work fine as well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.