GGplot - R - Second Axis on Color / Group - Long Format

Viewed 82

unfortunately i struggel with the GGPlot and the secondary axis. I created a long format of data with three categories i want to display in a GGplot. 1 should be displayed as a multiplot, 1 is the color 1 is the line type. like here in the chart!

enter image description here

The Problem i have now is, that i am not aware how to integrate a secondary axis for the "dotted lines" for example. Alternative i could just flip the data and include the second axis for the color, but i assume this is the very same problem. Thanks in advance!

this is the code i have so far.

#test 
cat1 <- c(rep("A",10),rep("B",10),rep("A",10),rep("B",10),rep("A",10),rep("B",10),rep("A",10),rep("B",10))
cat2 <- c(rep("A",10),rep("B",10),rep("B",10),rep("A",10),rep("A",10),rep("B",10),rep("B",10),rep("A",10))
steps <- c(seq(1,10),seq(1,10),seq(1,10),seq(1,10),seq(1,10),seq(1,10),seq(1,10),seq(1,10))
sz <- c(rep(1,40),rep(2,40))
data <- c(cumsum(exp(rnorm(10))),(rnorm(10))/100,cumsum(exp(rnorm(10))),(rnorm(10))/100,cumsum(exp(rnorm(10))),(rnorm(10))/100,cumsum(exp(rnorm(10))),(rnorm(10))/100)

df <- data.frame("Category1" = cat1,
                 "Category2" =cat2,
                 "Steps" = steps,
                 "Szenario" = sz,
                 "Value" = data)


ggplot(df,aes(x=Steps,y=Value,group=interaction(Category1,Category2),color=Category2,linetype=Category1))+
  geom_line()+
  facet_wrap(facets=vars(Szenario),scales="free")
1 Answers

UPdate:

df1 <- df %>% 
  mutate(Value = ifelse(Category1=="B", Value*100, Value))
ggplot(df1,aes(x=Steps,y=Value,group=interaction(Category1,Category2),color=Category2,linetype=Category1))+
  geom_line()+
  facet_wrap(facets=vars(Szenario),scales="free") +
  scale_y_continuous("Category1",
                     sec.axis = sec_axis(trans = ~ . * (min(df$Value)/max(df$Value)),
                                         name = 'Category2'))

enter image description here

You could scale_y_continuous:

ggplot(df,aes(x=Steps,y=Value,group=interaction(Category1,Category2),color=Category2,linetype=Category1))+
  geom_line()+
  facet_wrap(~Szenario, scales = "free_y") +
  scale_y_continuous("Category1",
                     sec.axis = sec_axis(trans = ~ . * (min(df$Value) / max(df$Value)),
                                         name = 'Category2'))

enter image description here

Related