billbrad
billbrad

Reputation: 7

How to make a ggplot with one 'x' value and multiple 'y' values

I am trying to create a line/point plot with ggplot and I am having difficulty figuring out how to create 3 separate lines on one graph. I want the graph to have 1 line for each type of activity(Gym, Yoga, Walk) and the x axis being the Month, and y axis being the number of days.

This is my data:

>### Self-care Tracker ###
> 
> library(tidyverse)
> 
> Month <- c("January", "February", "March", "April", "May", "June", "July",
+            "August", "September", "October", "November", "December")
>   
> Gym <- c(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
> Yoga <- c(2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1) 
> Walk <- c(3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
> 
> 
> self.care <- tibble(Month, Gym, Yoga, Walk)
> self.care
# A tibble: 12 x 4
   Month       Gym  Yoga  Walk
   <chr>     <dbl> <dbl> <dbl>
 1 January       3     2     3
 2 February      1     1     1
 3 March         1     1     1
 4 April         1     1     1
 5 May           1     1     1
 6 June          1     1     1
 7 July          1     1     1
 8 August        1     1     1
 9 September     1     1     1
10 October       1     1     1
11 November      1     1     1
12 December      1     1     1

This is one attempt at plotting:

> ggplot() +
+   geom_line(self.care, aes(x = Month, y = Gym)) +
+   geom_line(self.care, aes(x = Month, y = Yoga)) +
+   geom_line(self.care, aes(x = Month, y = Walk))
Error: `mapping` must be created by `aes()'

I also tried putting the data in the argument for ggplot, like so:

ggplot(self.care, aes(x = Month, y = c(Gym, Yoga, Walk)) +
  geom_point() + geom_line()

which resulted in no errors, but the graph didn't look right: Failed Data Table

I also tried a wider tibble: I had a vector for each month with 3 numeric values, so each month was a column. Unfortunately, I did not save the code for that, but in short, it didn't work. Any other ideas of how I can organize the data so that it can be plotted?

Upvotes: 0

Views: 10020

Answers (1)

I think it is easier to change your data from wide to long format and then plot it. The y data is the same for the three activities, so Gym is not visible (it becomes masked by Yoga lines and points).

library(ggplot2)
library(tidyverse)
self.care <- tibble(Month, Gym, Yoga, Walk)
self.care <- self.care %>% pivot_longer(cols = c(Gym, Yoga, Walk),
                           names_to = "Activity")

ggplot(self.care,aes(x = Month, 
                     y = value, 
                     col = Activity, 
                     group = Activity)) +
  geom_line() + 
  geom_point() + 
  #To set x axis labels as vertical 
  theme(axis.text.x = element_text(angle = 90, 
                             hjust = 1,
                             vjust = 0.5))

Rplot with point and lines

Upvotes: 4

Related Questions