require 'csv'

csv_file_path = 'wajima_population'

data = []
CSV.foreach(csv_file_path,headers: true)do |row|
 data << [row['Year'].to_i,row['population'].to_i]
end

r_script = <<-RSCRIPT
# 必要なパッケージを読み込み
install.packages("ggplot2")
library(ggplot2)

data <- data.frame(
 Year = c(#{data.map { |row| row[0] }.join(', ')}),
 Population = c(#{data.map { |row| row[1]}.join(', ')})
)

ggplot(data, aes(x = Year, y = population)) +
 geom_line() +
 labs(title = "輪島市の人口の推移",x = "月" , y = "人口")
RSCRIPT

File.write('plot_population.R', r_script)

system('Rscript plot_population.R')
