Foundation of ggplot2
ggplot2是一款R中实用的绘图包,常用于数据科学。代码中引用的数据来自钻石的各项参数——克拉(carat),切工(cut),颜色(color)和净度(clarity),还有五个物理指标——深度(depth),钻面宽度(table),x,y和z
code(1)
library(ggplot2) #调用ggplot2
set.seed(1410) #让样本可重复
dsmall <- diamonds[sample(nrow(diamonds),100),] #原始数据的一个样本为100的随机样本
qplot(carat, price, data = diamonds, alpha = I(1/100)) # x = carat y = price data = 数据文件名 alpha = I()透明度
调整透明度,淡化散点,可以看出数据点集中(重叠)的地方
图1-1
Code(2)
library(ggplot2)
qplot(carat, price, data = diamonds, alpha = I(1/200))
图1-2与图1-1比较,code(2)中的透明度改为1/200,淡化了其中重叠区域的颜色,让重叠密集的区域显现出来。
图1-2
Code(3)
qplot(carat, price, data = dsmall, geom = c('point', 'smooth'))
Code(3)向图中添加平滑曲线
图1-3
code(4)
qplot(carat, price, data = diamonds, geom = c('point', 'smooth'))
1-4
code(5)
qplot(carat, price, data = dsmall, geom = c('point', 'smooth'),span = 0.2)
1-5
code(6)
qplot(carat, price, data = dsmall, geom = c('point', 'smooth'), span = 1)
1-6
code(7)
qplot(color, price/carat, data = diamonds, geom = "jitter", alpha = I(1/5))
1-7
code(8)
qplot(carat, data = diamonds, geom = "histogram")
1-8
code(9)
qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.1, xlim = c(0,3))
1-9
code(10)
qplot(carat, data = diamonds, geom = "histogram", binwidth = 0.01, xlim = c(0,3))
1-10
code(11)
qplot(carat, data = diamonds, geom = "histogram", fill = color)
1-11
code(12)
qplot(carat, data = diamonds, geom = "density")
1-12
code(13)
qplot(carat, data = diamonds, geom = "density", colour = color)
1-13
参考书目
[1] ggplot2: 数据分析与图形艺术
[2] R语言实战 (第2版)