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

138 阅读2分钟

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

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

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

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

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

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

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

下面我们带来的是关于 坐标系设置对映射aes的控制分面主题

坐标系设置

ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
  geom_point() +
  coord_flip()

image.png

ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
  geom_point() +
  coord_polar(theta = "x")

image.png

ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
  geom_point() +
  coord_trans(x = "log", y = "log")

image.png

ggplot(data = d500, aes(x = cut, fill = cut)) +
  geom_bar() + 
  coord_polar(theta = "x")

image.png

ggplot(data = d500, aes(x = cut, fill = cut)) +
  geom_bar() + 
  coord_polar(theta = "y")

image.png

ggplot(data = d500, aes(x = factor(1), fill = cut)) +
  geom_bar()

image.png

ggplot(data = d500, aes(x = factor(1), fill = cut)) +
  geom_bar() +
  coord_polar(theta = "y")

image.png

# 其它类型的 geom
# 密度图 geom_density
ggplot(data = d500, aes(x = carat)) +
  geom_density()

image.png

# 二维密度图
ggplot(data = d500, aes(x = carat, y = price)) +
  geom_density_2d()

image.png

# 二维密度图
ggplot(data = d500, aes(x = carat, y = price)) +
  geom_bin2d()

image.png

# 二维密度图
ggplot(data = d500, aes(x = carat, y = price)) +
  geom_hex()

image.png

# 面积图 geom_area
ggplot(data = d500, aes(x = cut, fill = cut)) +
  geom_area(stat = "density")

image.png

对映射aes的控制

ggplot(data = d500, aes(x = carat, y = price)) +
  geom_point() +
  scale_y_log10() # 观察纵坐标的刻度变化

image.png

ggplot(data = d500, aes(x = carat, y = price, color = price)) +
  geom_point()

image.png

ggplot(data = d500, aes(x = carat, y = price, color = price)) +
  geom_point() +
  scale_color_gradient(low="yellow", high="red")

image.png

分面

ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
  geom_point() +
  facet_wrap(~cut)

image.png

ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
  geom_point() +
  facet_wrap(~clarity)

image.png

ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
  geom_point() +
  facet_grid(cut~clarity)

image.png

主题

ggplot(data = d500, aes(x = price, fill = cut)) +
  geom_area(stat = "density")

image.png

ggplot(data = d500, aes(x = price, fill = cut)) +
  geom_area(stat = "density") +
  theme_bw()

image.png

ggplot(data = d500, aes(x = price, fill = cut)) +
  geom_area(stat = "density") +
  theme_dark()

image.png

结尾

关于 ggplot2 的补充就到此结束啦,给大家提供非常多的画图方式,大家可以参考并结合使用,RStudio 是个非常好用的可视化工具。