Home > Mobile >  Plotting geom_line with two columns for two categories for two years
Plotting geom_line with two columns for two categories for two years

Time:04-15

I have a dataframe which looks something like below:

#sample dataframe
set.seed(42)
dates <- seq.Date(as.Date("2012-01-01"), as.Date("2013-12-30"), "day")
n <- length(dates)
dat <- data.frame(created_at = dates,
                  category = rep(LETTERS[1:2], n/2),
                  Value_A = sample(18:100, n, replace=TRUE),
                  Value_B = sample(101:200, n, replace=TRUE))

I am trying to plot the count of Value_A and Value_B for category A & B Year Wise.

I am using the following code to plot it.

#adding year column
dat <- dat %>% 
  mutate(year=lubridate::year(dat$created_at))

#plotting data
ggplot(data = dat, aes(x = created_at))  
  geom_line(aes(y = Value_A, colour = category)) 
  geom_line(aes(y = Value_B, colour = category)) 
  facet_wrap(~ year, ncol = 1, scales = "free_x")  
  labs(title = 'Value_A and Value_B Count',
       x = 'Time',
       y = 'Count')  
  theme_bw()  
  scale_x_date(date_breaks = '1 month', date_labels = "%b", expand = expansion(0,0)) 
  scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                labels = trans_format("log10", math_format(10^.x))) 
  theme(text=element_text(size=13),panel.spacing.x=unit(0.6, "lines"),
        panel.spacing.y=unit(1, "lines"), legend.position="bottom") 
  scale_linetype_manual(name = NULL, values = 2)

And this is how the plot looks like: enter image description here

I want both Value_A & Value_B to be differentiated on color based on categories so it would make more sense.

Since I am already using colour = category in geom_line. I cannot add any specific colors.

Any guidance please?

CodePudding user response:

Instead of mapping just category on the color aes you could expand the number of categories and colors by mapping e.g. paste0(category, "_A") and paste0(category, "_B") on the color aes:

library(ggplot2)
library(scales)

ggplot(data = dat, aes(x = created_at))  
  geom_line(aes(y = Value_A, colour = paste0(category, "_A")))  
  geom_line(aes(y = Value_B, colour = paste0(category, "_B")))  
  facet_wrap(~year, ncol = 1, scales = "free_x")  
  labs(
    title = "Value_A and Value_B Count",
    x = "Time",
    y = "Count"
  )  
  theme_bw()  
  scale_x_date(date_breaks = "1 month", date_labels = "%b", expand = expansion(0, 0))  
  scale_y_log10(
    breaks = trans_breaks("log10", function(x) 10^x),
    labels = trans_format("log10", math_format(10^.x))
  )  
  theme(
    text = element_text(size = 13), panel.spacing.x = unit(0.6, "lines"),
    panel.spacing.y = unit(1, "lines"), legend.position = "bottom"
  )  
  scale_linetype_manual(name = NULL, values = 2)

  • Related