如何在 R 中使用 ggplot2 保存绘图?
在本文中,我们将看到如何在 R 编程语言中保存 GGPlot。 ggplot2 是 R 中的绘图包,用于根据数据框中指定的数据创建复杂的绘图。它提供了一个更具编程性的界面,用于指定要在图形设备上绘制的变量、它们的显示方式以及一般的视觉属性。可以使用以下语法安装包并将其下载到工作空间中:
install.packages("ggplot2")
ggplot() 方法用于在屏幕上创建不同类型的绘图。它用于将数据框绑定到绘图的数据参数。它还用于使用图形的 aes() 属性定义美学和组件映射。它用于通过选择要绘制的变量以及如何在图形中显示它们来创建复杂的图,例如坐标、形状、颜色等。图形表示也可以以特定于几何图形的形式创建要创建的绘图类型。
ggplot (data , mapping = aes(x, y)) + geom_point()
方法一:使用ggsave()
ggsave() 是 ggplot2 包中的一个方法,用于保存屏幕上显示的最后一个绘图。它还假设来自指定扩展的图形设备类型。需要在函数调用中指定文件名。绘图可以使用 .png 或 .pdf 扩展名保存。
Syntax: ggsave( filename, plot = last_plot(), width = NA, height = NA, units = c(“in”, “cm”, “mm”), path )
Arguments :
- filename – The character string name to assign to the plot
- plot – By default, it is used to save the last displayed plot.
- width, height, units – The dimensions of the plot
- path – The path to save the image can also be specified
代码:
R
# importing the reqd libraries
library(ggplot2)
# defining the x and y coordinates
xpos <- 1:5
ypos <- xpos**3
# creating a data frame
data_frame <- data.frame(xpos = xpos, ypos = ypos)
# creating a plot
graph <- ggplot(data_frame, aes(xpos,ypos)) +
geom_point()
# saving the plot as pdf
ggsave("cubegfg.pdf", graph, path = "/Users/mallikagupta/Desktop")
R
# importing the reqd libraries
library(ggplot2)
# defining the x and y coordinates
xpos <- 1:5
ypos <- xpos**3
# creating a data frame
data_frame <- data.frame(xpos = xpos, ypos = ypos)
# creating a plot
graph <- ggplot(data_frame, aes(xpos,ypos)) +
geom_point()
png("Check.png")
print(graph)
dev.off()
输出
Saving 7.47 x 5.96 in image
也可以不使用 ggsave() 方法将绘图保存到工作空间。 R 中的 png() 方法可用于将 png 格式的 ggplot 保存到指定目录中。可以将绘图名称和路径名称指定为该方法的参数。
png(plot-path)
方法 2:使用 dev.off()
然后使用 dev.off() 方法终止此图形设备窗口并保存绘图。
电阻
# importing the reqd libraries
library(ggplot2)
# defining the x and y coordinates
xpos <- 1:5
ypos <- xpos**3
# creating a data frame
data_frame <- data.frame(xpos = xpos, ypos = ypos)
# creating a plot
graph <- ggplot(data_frame, aes(xpos,ypos)) +
geom_point()
png("Check.png")
print(graph)
dev.off()
输出: