In my actual code, I made a plot for a df exactly the way I want with a lot of commands. I then need to make five more plots with the same df, but I need to use different columns from that df.
I'm trying to avoid the copy and paste method and manually changing things. So I tried to create a custom function, but I'm not getting it to work right.
Below demonstrates my issue with mtcars.
The first chunk creates the plot by first using dplyr to summarize the data and then throw it in a plot. As a new user, I'm only allowed one image in my post, so you'll have to run the code to see the plot I'm trying to reproduce in my function.
The next section is trying to turn that plot command into a function, but when I use the function, you can see the plot is not coming out right.
I can't seem to find the solution from all of my searches and trial and error, so any help will be greatly appreciated. My system info is a the bottom.
Thanks in advance for the help.
library(tidyverse)
mtcars %>%
group_by(cyl,hp) %>%
summarize(mpg = sum(mpg)) %>%
ggplot(aes(x = cyl, y = hp, size = mpg)) +
geom_point()
plot_func <- function(df,xcol,ycol){
df %>%
group_by_(xcol,ycol) %>%
summarize(mpg = sum(mpg)) %>%
ggplot(aes(x=xcol,y = ycol, size = mpg)) +
geom_point()
}
plot_func(mtcars,"cyl","hp")
Created on 2019-01-24 by the reprex package (v0.2.0).
session info:
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
OS: Windows 10 Enterprise