簡體   English   中英

R:如何使用ggplot中的循環在一個圖中繪制多條線

[英]R: How to plot multiple lines in one plot using a loop in ggplot

我正在R中使用ggplot創建圖,並且使用了循環以加快繪制時間。 但是我在同一張圖中繪制多條線時遇到了問題。 數據:

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

一些數據

  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

我正在使用的循環基於此處 ,如下所示:

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)

我想做的是分別為每個LDI值繪制多條線(因此是CperkWh圖)。 當我運行該程序時,所收到的圖就是我想要的,但是geom_line命令連接了所有點,我希望它僅將點與LDI值相同。 這就是現在發生的情況: 在此處輸入圖片說明

誰能幫我?

很難說出您要在沒有數據的情況下要做什么,但是為什么您完全需要此循環? 這樣的事情應該起作用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM