本文已参加「新人创作礼」活动,一起开启掘金创作之路。
这次带来的是 RStudio 的图形系统 - 补充 其二。
补充: 第三方绘图包 ggplot2
介绍
ggplot2
是R
中非常流行的绘图系统, 它是现代图形语法的一种实现. 自从问世以来已经获得了巨大成功, 并被移植到了其它数据科学语言中(比如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()
ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
geom_point() +
coord_polar(theta = "x")
ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
geom_point() +
coord_trans(x = "log", y = "log")
ggplot(data = d500, aes(x = cut, fill = cut)) +
geom_bar() +
coord_polar(theta = "x")
ggplot(data = d500, aes(x = cut, fill = cut)) +
geom_bar() +
coord_polar(theta = "y")
ggplot(data = d500, aes(x = factor(1), fill = cut)) +
geom_bar()
ggplot(data = d500, aes(x = factor(1), fill = cut)) +
geom_bar() +
coord_polar(theta = "y")
# 其它类型的 geom
# 密度图 geom_density
ggplot(data = d500, aes(x = carat)) +
geom_density()
# 二维密度图
ggplot(data = d500, aes(x = carat, y = price)) +
geom_density_2d()
# 二维密度图
ggplot(data = d500, aes(x = carat, y = price)) +
geom_bin2d()
# 二维密度图
ggplot(data = d500, aes(x = carat, y = price)) +
geom_hex()
# 面积图 geom_area
ggplot(data = d500, aes(x = cut, fill = cut)) +
geom_area(stat = "density")
对映射aes的控制
ggplot(data = d500, aes(x = carat, y = price)) +
geom_point() +
scale_y_log10() # 观察纵坐标的刻度变化
ggplot(data = d500, aes(x = carat, y = price, color = price)) +
geom_point()
ggplot(data = d500, aes(x = carat, y = price, color = price)) +
geom_point() +
scale_color_gradient(low="yellow", high="red")
分面
ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
geom_point() +
facet_wrap(~cut)
ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
geom_point() +
facet_wrap(~clarity)
ggplot(data = d500, aes(x = carat, y = price, color = cut)) +
geom_point() +
facet_grid(cut~clarity)
主题
ggplot(data = d500, aes(x = price, fill = cut)) +
geom_area(stat = "density")
ggplot(data = d500, aes(x = price, fill = cut)) +
geom_area(stat = "density") +
theme_bw()
ggplot(data = d500, aes(x = price, fill = cut)) +
geom_area(stat = "density") +
theme_dark()
结尾
关于 ggplot2
的补充就到此结束啦,给大家提供非常多的画图方式,大家可以参考并结合使用,RStudio
是个非常好用的可视化工具。