I've been trying to write an R code which reads data from an excel file and plot different graph charts (like: bar, line, point or pie) based on the user input, using the ggplot package.
For this, I am using a 3-4 different functions:
1) function for Bar plotting:
bar <- function() {
plot <- ggplot (data= df, aes(x= Dates, y= Values))
barPlot <- plot + geom_bar(stat="identity", fill="red", width=1)
print(barPlot)
}
2)Similarly, for line plot :
line <- function() {
plot <- ggplot (data= df, aes(x= Dates, y= Values))
linePlot <- plot + geom_line(aes(group=1), colour="blue", size=0.5)
print(linePlot)
}
3) The main function, which declares all the libraries and reading the excel workbook as a data frame.
In the main function I am trying to call the different plot functions using "if else" as follows:
main <- function() {
library(XLConnect)
library(ggplot2)
wk <- loadWorkbook("D:\\....xlsx")
dataFrame = readWorksheet (wk, sheet="sheet1", header=TRUE)
df <- data.frame(Dates = dataFrame[,1],
Values =dataFrame[,2])
name <- scan(what = " ")
if (name == "bar")
{ bar() }
else if (name == "line")
{ line() }
}
But it throws back the error: " ggplot2 doesn't know how to deal with data of class function".
Simplified Version of the Data:
Dates Values
Jan 46
Feb 54
Mar 32
How can I modify my code to accommodate this requirement of being able to plot different graphs as per user input?