Hey @esa_chris ,
you are almost there. You can try the following:
library("ggplot2")
df <- mtcars
df$rown <- seq.int(nrow(df))
variable = "mpg" # needs to be a string, which can then be changed.
ggplot() +
geom_line(data = df, aes(x=rown, y=mpg)) +
labs(
y = variable, # add title for y axis,
title = "PLot title", # add plot title
)
There are other arguments in the labs()
function as well, such as subtitle of the plot, caption and x axis title. Above is one way of doing it. However, if you want to avoid assigning a value to a named object, such as variable
in this case, you can try the following.
library("ggplot2")
df <- mtcars
df$rown <- seq.int(nrow(df))
create_chart <- function(data,x_var,y_var){
data|>
ggplot() +
geom_line(aes(x= .data[[x_var]], y= .data[[y_var]])) +
labs(
y = y_var, # add title for y axis,
title = "PLot title", # add plot title
)
}
create_chart(data = df,x_var = "rown",y_var = "mpg")
create_chart(data = df,x_var = "rown",y_var = "hp")
Hope this helps,
Ayush