Plot inside a loop using highcharter

雨燕双飞 提交于 2019-12-11 06:45:14

问题


I am using highcharter for my graphs. I have different courses, which I need to draw same graphs for all. I am trying to have a for loop over courses and plot these graphs inside my loop. The problem that it doesnt plot anything inside the loop and it works fine from outside the loop.

for(i in unique(my_data$CourseID)){
  courseData<-subset(my_data, my_data$CourseID== i)

  #Course by Majer
  byMajer <- table(courseData$MajerName)
  #barplot(byMajer, main="Students by Majer", xlab="Majers") 

  byM <- aggregate(courseData$MajerName, by=list(courseData$MajerName), FUN=length)

  hc <- highchart(debug = TRUE) %>% 
  hc_title(text = courseData$CourseName[1]) %>% 
  hc_chart(type = "column") %>% 
  hc_xAxis(categories = byM$Group.1) %>% 
  hc_add_series(data = byM$x)

  #this is not working. it shows nothing.
  hc

  #but if I try to have this, it works, I will use below variables outside the loop
  assign(paste("hc",i,sep=""), hc)
}

#Below graphs showing in the output. I need to get rid of them and use the one inside the loop.
hc1; hc2; hc3; hc4; hc5; hc6; hc7; hc8; hc9; hc10; hc11; hc12; hc13; hc14; hc15; hc16; hc17; hc18

回答1:


Answer to the problem is here: https://stackoverflow.com/a/4716380/4046096

In short: Automatic printing is turned off in a loop, so you need to explicitly print something.

Instead of hc use print(hc).

I do not have your data, but this code works fine:

for(i in c(1,2,3,4,5)){
  hc <- highchart(debug = TRUE) %>% 
  hc_chart(type = "column") %>% 
  hc_add_series(data = list(1, i, i * 2, 5))

  print(hc)
}


来源:https://stackoverflow.com/questions/40915969/plot-inside-a-loop-using-highcharter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!