可视化:RStudio 图形系统 - 补充 其一

本文已参加「新人创作礼」活动,一起开启掘金创作之路。

这次带来的是 RStudio 的图形系统 - 补充 其一。

补充: 第三方绘图包 ggplot2 介绍

ggplot2R中非常流行的绘图系统, 它是现代图形语法的一种实现. 自从问世以来已经获得了巨大成功, 并被移植到了其它数据科学语言中(比如Python).

ggplot2根据现代图形语法理论, 将图形分为以下几个部分:

  • data 数据来源
  • mapping 映射
  • geom_xxxx,geom 几何对象函数
  • stat_xxxx,stat 统计变换函数
  • coord_xxxx 坐标系设置
  • scale_xxxx 控制映射方式
  • facet_xxxx 分面设置
  • theme_xxxx 主题设置
  • 用加号+连接不同的图层

其中前三个部分是必须由用户指定的, 后面几个部分有默认值(根据前三者不同而使用不同的默认值), 当这些部分没有被指定时会使用对应的默认值, 当然用户也可以通过主动设置来得到不同的效果.

准备数据

library(dplyr)
library(ggplot2)

# 准备数据, 从diamonds数据集中随机选择500个钻石样本
set.seed(2021)
rows = sample(nrow(diamonds), 500)
d500 = diamonds[rows,]

# 使用dplyr做筛选的写法
set.seed(2021)
diamonds %>% sample_n(size = 500) -> d500
复制代码

数据和映射经常是写在同一个图层中的: data, mapping

ggplot(data = d500, mapping = aes(x = carat, y = price))
复制代码

image.png

再加上geom层就能构成一个最简图形

ggplot(data = d500, mapping = aes(x = carat, y = price)) +
  geom_point()
复制代码

image.png

ggplot(data = d500, mapping = aes(x = carat, y = price)) +
  geom_line()
复制代码

image.png

ggplot(data = d500, mapping = aes(x = carat, y = price)) +
  geom_col()
复制代码

image.png

ggplot(data = d500, mapping = aes(x = carat, y = price)) +
  geom_hex()
复制代码

image.png

设置点的大小,形状,颜色,透明度等参数

ggplot(data = d500, mapping = aes(x = carat, y = price)) +
  geom_point(size = 2, pch = 6, color = "red", alpha = 0.3) # alpha 用来设置透明度
复制代码

image.png

理解这些设置在aes(…)内部和外部的区别

ggplot(data = d500, mapping = aes(x = carat, y = price, color = cut, size = carat)) +
  geom_point(pch = 18)
复制代码

image.png

下面是一些常用geom_xxxx函数

# 散点图 geom_point

# 线图 geom_line

# 条形图 geom_bar
ggplot(data = d500, aes(x = cut)) +
  geom_bar()
复制代码

image.png

ggplot(data = d500, aes(x = cut)) +
  geom_bar(color = "orange", fill = "white")
复制代码

image.png

ggplot(data = d500, aes(x = cut, color = cut)) +
  geom_bar(fill = "white")
复制代码

image.png

ggplot(data = d500, aes(x = cut, fill = cut)) +
  geom_bar()
复制代码

image.png

ggplot(data = d500, aes(x = cut, fill = clarity)) +
  geom_bar()
复制代码

image.png

ggplot(data = d500, aes(x = cut, fill = clarity)) +
  geom_bar(position = "dodge")
复制代码

image.png

ggplot(data = d500, aes(x = cut, fill = clarity)) +
  geom_bar(position = "fill")
复制代码

image.png

# 直方图 geom_histogram
ggplot(data = d500, aes(x = carat)) +
  geom_histogram()
复制代码

image.png

ggplot(data = d500, aes(x = carat)) +
  geom_histogram(color = "white")
复制代码

image.png

ggplot(data = d500, aes(x = carat, fill = cut)) +
  geom_histogram(color = "white")
复制代码

image.png

# 箱线图 geom_boxplot
ggplot(data = d500, aes(x = carat)) +
  geom_boxplot()
复制代码

image.png

ggplot(data = d500, aes(y = carat)) +
  geom_boxplot()
复制代码

image.png

ggplot(data = d500, aes(x = factor(1), y = carat)) +
  geom_boxplot()
复制代码

image.png

ggplot(data = d500, aes(x = cut, y = carat)) +
  geom_boxplot(color = "#377EB8")
复制代码

image.png

ggplot(data = d500, aes(x = cut, y = carat, fill = cut)) +
  geom_boxplot()
复制代码

image.png

猜你喜欢

转载自juejin.im/post/7107148535623237646
今日推荐