How to use rect with theme() In R Language
In this approach, after the plot has been created normally, theme() function is added to it with rect parameter. To rect, element_rect() function is passed with parameter fill set to transparent.
Syntax: theme(rect = element_rect(fill=”transparent”))
Example: Plot with transparent background
R
library (ggplot2) function1<- function (x){x**2} function2<- function (x){x**3} function3<- function (x){x/2} function4<- function (x){2*(x**3)+(x**2)-(x/2)} df= data.frame (x=-2:2, values= c ( function1 (-2:2), function2 (-2:2), function3 (-2:2), function4 (-2:2)), fun= rep ( c ( "function1" , "function2" , "function3" , "function4" )) ) plt<- ggplot (df, aes (x,values,col=fun))+ geom_line ()+ theme (rect = element_rect (fill = "transparent" )) ggsave (plt, filename = "output.png" , bg = "transparent" ) |
Output:
How to make graphics with transparent background in R using ggplot2?
In this article, we will discuss how to create graphs with transparent background in R programming language.
The required task will be achieved by using theme() function with appropriate parameters. theme() function used to modify theme settings. To actually visualize a transparent background the image has to be stored as a PNG image, this can be done ggsave() function.
Syntax: ggsave(plot, filename, bg)
Parameter:
- plot: plot to be saved
- filename: path of the file
- bg: background
Create a simple plot for demonstration:
R
library (ggplot2) function1<- function (x){x**2} function2<- function (x){x**3} function3<- function (x){x/2} function4<- function (x){2*(x**3)+(x**2)-(x/2)} df= data.frame (x=-2:2, values= c ( function1 (-2:2), function2 (-2:2), function3 (-2:2), function4 (-2:2)), fun= rep ( c ( "function1" , "function2" , "function3" , "function4" )) ) plt<- ggplot (df, aes (x,values,col=fun))+ geom_line () ggsave (plt, filename = "output1.png" ) |
Output:
Contact Us