Reputation: 837
I have the following dataframe data
. I'm trying to create a lineplot using ggplot
, where I have 2 lines (the two dates under Date
), Key
as my x-axis, Value
as my Y axis.
structure(list(Date = c("2020-11-01", "2020-11-28", "2020-11-01",
"2020-11-28", "2020-11-01", "2020-11-28", "2020-11-01", "2020-11-28",
"2020-11-01", "2020-11-28", "2020-11-01", "2020-11-28", "2020-11-01",
"2020-11-28"), Key = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L,
4L, 5L, 5L, 6L, 6L, 7L, 7L), .Label = c("3M", "2YR", "5YR", "10YR",
"20YR", "25YR", "30YR"), class = "factor"), Value = c(3.6, 4.25,
4.22, 4.37, 7.09, 7.065, 9.315, 8.96, 11.65, 11.05, 11.77, 11.145,
11.73, 11.075)), row.names = c(NA, -14L), class = "data.frame")
here is the code I'm using for my plot. However, its not coming out as desired (the curves aren't appearing on the plot, added an image below)
ggplot(dat2, aes(x = Key, y = Value, col = Date)) +
geom_line()
This is how I would want it to appear like
Upvotes: 2
Views: 1772
Reputation: 8699
You will need to set the group aesthetic. By default, ggplot2 will set the group aesthetic to the interaction of all discrete variables. In your case, this results in each row being its own group, meaning no lines are actually drawn. Setting the group aesthetic results in the correct graphic being produced:
ggplot(dat2, aes(x = Key, y = Value, col = Date, group=Date)) +
geom_line()
Upvotes: 3
Reputation: 886938
An option is to convert the 'Key' to numeric
, plot and then change the x axis
library(dplyr)
library(ggplot2)
dat2 %>%
mutate(Keyn = as.numeric(factor(Key))) %>%
ggplot(aes(x = Keyn, y = Value, col = Date)) +
geom_line() +
scale_x_continuous(breaks = unique(as.numeric(factor(dat2$Key))),
labels = unique(dat2$Key))
Upvotes: 1