Reputation: 97
My data looks like this:
> head(mydata, 24)
time exp2
1 Jan-99 24977.25
2 Feb-99 21186.07
3 Mar-99 41245.92
4 Apr-99 47.57
5 May-99 25254.42
6 Jun-99 164.95
7 Jul-99 9629.81
8 Aug-99 164.95
9 Sep-99 47091.12
10 Oct-99 0.09
11 Nov-99 3458.64
12 Dec-99 24.00
13 Jan-00 28636.17
14 Feb-00 23850.65
15 Mar-00 23680.16
16 Apr-00 513.82
17 May-00 252.17
18 Jun-00 178.10
19 Jul-00 20293.85
20 Aug-00 474.16
21 Sep-00 164.95
22 Oct-00 164.95
23 Nov-00 164.95
24 Dec-00 96.10
>
I would like to create a simple graph in ggplot, using:
newdata2 <- mydata %>%
mutate(date = as.Date(time, format = "%m/%y"))
ggplot(newdata2, aes(x = time, y = exp2)) +
geom_line(color = "darkorchid4")
The error is:
geom_path: Each group consists of only one observation. Do you need to adjust
the group aesthetic?
When running:
mydata$time <- as.Date(mydata$time, format = "%m/%y")
ggplot(mydata, aes(x = time, y = exp2)) +
geom_line(color = "darkorchid4")
I get this error:
Error in seq.int(0, to0 - from, by) : 'to' must be a finite number
I can't understand why this error. Can you help me please?
Upvotes: 1
Views: 3671
Reputation: 18682
To connect the points set group = 1
in your aes
:
ggplot(df, aes(x = time, y = exp2, group = 1)) +
geom_line(color = "darkorchid4")
If time
is of class character then you need to convert it to a date object before you can change the format:
format(as.Date(paste0(df$time, "-01"), "%b-%y-%d"), "%m/%y")
[1] "01/99" "02/99" "03/99" "04/99" "05/99" "06/99" "07/99" "08/99" "09/99" "10/99" "11/99"
[12] "12/99" "01/00" "02/00" "03/00" "04/00" "05/00" "06/00" "07/00" "08/00" "09/00" "10/00"
[23] "11/00" "12/00"
Which can be used in your mutate
function like:
df %>%
mutate(date = format(as.Date(paste0(time, "-01"), "%b-%y-%d"), "%m/%y"))
Update
The above code will convert your values to a character
object. Since you want to plot by and adjust the x-axis using scale_x_date
then it needs to be a Date
object. To give you an idea of what's possible here is a reproducible example:
library(ggplot2)
library(dplyr)
df %>%
mutate(date = as.Date(paste0(time, "-01"), "%b-%y-%d")) %>%
ggplot(aes(x = date, y = exp2, group = 1)) +
geom_line(color = "darkorchid4") +
geom_col(width = 2, fill = "red") +
scale_x_date(date_breaks = "2 months",
date_labels = "%b-%y") +
theme(axis.text.x = element_text(angle = 90))
Data
df <- structure(list(time = c("Jan-99", "Feb-99", "Mar-99", "Apr-99",
"May-99", "Jun-99", "Jul-99", "Aug-99", "Sep-99", "Oct-99", "Nov-99",
"Dec-99", "Jan-00", "Feb-00", "Mar-00", "Apr-00", "May-00", "Jun-00",
"Jul-00", "Aug-00", "Sep-00", "Oct-00", "Nov-00", "Dec-00"),
exp2 = c(24977.25, 21186.07, 41245.92, 47.57, 25254.42, 164.95,
9629.81, 164.95, 47091.12, 0.09, 3458.64, 24, 28636.17, 23850.65,
23680.16, 513.82, 252.17, 178.1, 20293.85, 474.16, 164.95,
164.95, 164.95, 96.1)), row.names = c(NA, -24L), class = "data.frame")
Upvotes: 2