ggplot2, plotly, lattice, highcharter packages are used for creating well knwon descriptive plots in R. To use these plots in different in presentations or editing, it needs to be exported in appropriate format to the local machine.
In this recipe, we will demonstrate how to export images in R.
There are different ways to export images but we will use Cairo package to perform this task as it gives us the flexibility to format dimensions, background, resolution and type of image.
Creating a scatter plot Annual Income vs Age using Mall_customers dataset
# Data manipulation package library(tidyverse) # ggplot for data visualisation library(ggplot2) # reading a dataset customer_seg = read.csv('R_186_Mall_Customers.csv') # creating a scatter plot Annual Income vs Age fig = ggplot(customer_seg, aes(x = Annual.Income..k.., y = Age)) + geom_point(aes(color = Gender)) + labs(title = "Annual Income vs Age") fig
We will use Cairo package to export the plot image.
Syntax: Cairo(width = , height = , units =, file = , type , dpi = )
# loading Cairo package install.packages("Cairo") library(Cairo) # using Cairo function in the package Cairo::Cairo(file="Scatter_plot_PNG_96.png", type="png", width=7, height=5, units="in", dpi=96) fig invisible(dev.off) # to close the file