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")
Thanks for the swift response. I suppose I did not make myself very clear. I do not want to add captions, axis titles etc. What I had in mind is something like this
library("ggplot2")
df <- mtcars
df$rown <- seq.int(nrow(df))
variable = mpg
p <- ggplot() +
geom_line(data = df, aes(x=rown, y=variable))
p
I appreciate your feedback, but this is not really what I need. The variable I want to plot on the y-axis changes dynamically. It is not fruitful to manually change it as the name of the variable is the result of previous steps.
Is there no way to use a string that holds the name of the column that I want to use on the y-axis?
The above can be done by using the function shown in the previous reply.
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
)
}
variable <- "mpg" # a string that holds the name of the varible
create_chart(data = df,x_var = "rown",y_var = variable) # plots for rown vs mpg
variable <- "hp" # change the column name to be plotted on y axis
create_chart(data = df,x_var = "rown",y_var = variable) # plots for rown vs hp
Hi @esa_chris,
As @AyushBipinPatel has demonstrated, you can use the {rlang} .data pronoun to set the column name via variable with no need for a user-defined function:
library(ggplot2)
df <- mtcars
df$rown <- seq.int(nrow(df))
variable <- "mpg" # Beware, mpg is a separate inbuilt ggplot2 dataset
p <- ggplot() +
geom_line(data = df, aes(x=rown, y=.data[[variable]]))
p
How can a specify the actual color of the different lines manually using the function approach? The usual scale_color_manual does not work as it dose not accept the arguments of the function as an input. There is not error, but all the lines are in shades of grey.