# R编程中如何使用ggplot2包？用法示例指南

2021年4月3日17:05:45 发表评论 555 次浏览

#### 图层的构建块

• Aesthetics美学：x轴, y轴, 颜色, 填充, 大小, 标签, alpha, 形状, 线宽, 线型
• Geometrics几何学：点, 线, 直方图, 条形图, 箱线图
• Facets构面：列, 行
• Statistics统计：分档, 平滑, 描述性, 中间
• Coordinates坐标：笛卡尔, 固定, 极点, 极限
• Themes主题：非数据链接

#### 数据集

mtcars(汽车趋势汽车道路测试)包括油耗以及32辆汽车的10个方面的汽车设计和性能, 并预先安装了dplyr在R中打包。

``````# Installing the package
install.packages( "dplyr" )

library(dplyr)

# Summary of dataset in package
summary(mtcars)``````

#### 在数据集上执行ggplot2

``````# Installing the package
install.packages( "ggplot2" )

library(ggplot2)
library(dplyr)

# Data Layer
ggplot(data = mtcars)

# Aesthetic Layer
ggplot(data = mtcars, aes(x = hp, y = mpg, col = disp))

# Geometric layer
ggplot(data = mtcars, aes(x = hp, y = mpg, col = disp)) + geom_point()

ggplot(data = mtcars, aes(x = hp, y = mpg, size = disp)) + geom_point()

ggplot(data = mtcars, aes(x = hp, y = mpg, col = factor(cyl), shape = factor(am))) + geom_point()

# Histogram plot
ggplot(data = mtcars, aes(x = hp)) +
geom_histogram(binwidth = 5 )

# Facet Layer
p < - ggplot(data = mtcars, aes(x = hp, y = mpg, shape = factor(cyl))) + geom_point()

# Separate rows according to transmission type
p + facet_grid(am ~ .)

# Separate columns according to cylinders
p + facet_grid(. ~ cyl)

# Statistics layer
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() +
stat_smooth(method = lm, col = "red" )

# Coordinates layer: Control plot dimensions
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
geom_point() +
stat_smooth(method = lm, col = "red" ) +
scale_y_continuous( "mpg" , limits = c( 2 , 35 ), expand = c( 0 , 0 )) +
scale_x_continuous( "wt" , limits = c( 0 , 25 ), expand = c( 0 , 0 )) + coord_equal()

# Add coord_cartesian() to proper zoom in
ggplot(data = mtcars, aes(x = wt, y = hp, col = am)) +
geom_point() + geom_smooth() +
coord_cartesian(xlim = c( 3 , 6 ))

# Theme layer
ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() + facet_grid(. ~ cyl) +
theme(plot.background = element_rect(
fill = "black" , colour = "gray" ))

ggplot(data = mtcars, aes(x = hp, y = mpg)) +
geom_point() + facet_grid(am ~ cyl) +
theme_gray()``````

Coord_cartesian()适当放大

ggplot2提供各种类型的可视化。可以在包中使用更多参数, 因为包可以更好地控制数据的可视化。许多软件包都可以与ggplot2软件包集成, 以使可视化具有交互性和动画效果。