0
votes

I'm creating plots with ggplot in R and I used a loop in order to speed up my plotting time. However I have issues plotting multiple lines in the same graph. Data:

     df <- c("Results", "Capacity", "Power", "LDI","LDE", "LB", "PDC","D")

Some data

  Results Capacity Power  LDI      LDE  PDC   D     CperkWh
1 ImpactDC     1.00  PG20 LDI0.01  LDE0 PDC0 D10 0.010950532
2 ImpactDC     0.95  PG10 LDI0.02  LDE0 PDC0 D10 0.080374607
3 ImpactDC     0.90  PG50 LDI0.003 LDE0 PDC0 D10 0.010158171
4 ImpactDC     0.85  PG5  LDI0.05  LDE0 PDC0 D10 0.006994843
5 ImpactDC     0.80  PG3  LDI0.02  LDE0 PDC0 D10 0.009684512
6 ImpactDC     0.75  PG20 LDI0     LDE0 PDC0 D10 0.007891302

The loop I'm using is based on here and looks like this:

Power.graph <- function(df, na.rm = TRUE, ...){
  Powerlist <- unique(df$Power) 
  for (i in seq_along(Powerlist)){
    plot <- 
      ggplot(subset(df, df$Power==Powerlist[i]),
             aes(Capacity, y = CperkWh), group = df$Power, colour = PDC) +
      geom_line() +
      geom_point()+
      theme(axis.text.x = element_text(size=12))+
      facet_wrap( ~ PDC, ncol =1)+
      theme(legend.position = "none")+
      scale_y_continuous("Income  in €/kWh")+
      scale_x_continuous("Capacity of the line")+
      ggtitle(paste(Powerlist[i], ' Capacity of the line \n', 
                    "Income per kWh \n",
                    sep=''))
    #save plot as PNG 
    ggsave(plot = last_plot(), file= paste(StoreResults, '/Results/',
                                           Powerlist[i], "YesDCNoV2G.png", sep=''), scale=2)
    print(plot)
  }
}
#Run the function  
Power.graph(df)

What I would like to do is to plot multiple lines (so the graph CperkWh) for every value of LDI seperately. When I run the programme the plot I receive is what I want, however the geom_line command connects all the points and I would like it to only connect the point with the same value of LDI. This is what happen now: enter image description here

Can anyone help me?

1
Can you provide some sample data, rather than just your column names?cmaher
Seems like you might need to move group inside of aes. Try adding a reproducible example so folks can help you better.aosmith
Thank you for the tips: I have added some data.ima
@aosmith I moved the group part inside the aes, but nothing change: the lines are still attached to each other.ima
If you want to only connect lines for the same LDI value, then you can use group = LDI inside of aes. I think your colour should also be moved inside of aes,aosmith

1 Answers

0
votes

Tough to say what are you trying to do without your data, but why do you need this loop at all? Something like this should work:

ggplot(df, aes(Capacity, y = CperkWh, group=factor(Powerlist), color = PDC)) + 
  geom_line() +
  geom_point()