ggplot之六层参数
基本格式:
ggplot(Data数据集, Aesthetics坐标 + Geometries图形 + Facets分组 + Statistics +
Aesthetics
基本格式:
ggpplot(dataset, aes(x = 字段1, y = 字段2, color = 字段3, shape = 字段4, size = 字段5, ……))+
❗️label 和 shape 只能用于分类变量
❗️Aesthetics 和 图形Attributes参数辨析
Note: In this chapter you saw aesthetics and attributes. Variables in a data frame are mapped to aesthetics in aes(). (e.g. aes(col = cyl)) within ggplot(). Visual elements are set by attributes in specific geom layers (geom_point(col = "red")). Don't confuse these two things - here you're focusing on aesthetic mappings.
aes()放的是数据集里的变量,参数会跟着数据改变;geom()放的是图形的通常属性,全图统一。
例1
my_color <- "#4ABEFF"
# Set the fill aesthetic; color, size and shape attributes
ggplot(mtcars, aes(x = wt, y = mpg, fill = cyl))+
geom_point(col = my_color, size = 10, shape = 23)
Geometries
散点图:geom_point () 适用于连续变量,geom_jitter() 适用于分类变量
曲线图:geom_smooth()
条形图:geom_bar()
图形参数:position
❗️解决overplotting的好帮手--jitter()
jitter()使点分开,alpha使颜色变淡,shape使点变小,width可以修改不同类的点距离
例2
# Using the above plotting command, set the shape to 1
ggplot(Vocab, aes(x = education, y = vocabulary)) +
geom_jitter(alpha = 0.2, shape = 1)
Facets
按某字段分组,对每个分组做同样的图形
基本格式:facet_grid(. ~ 字段)
组合方式
全部写在一起
ggplot(mtcars, aes(x = wt, y = mpg, size = cyl)) +
geom_point()
主体分开
p = ggplot(data, aes(x = , y = ))
p + 不同图形
❗️好处:
可以保持主体不变,快速生成不同的图形;也可以在主体图上叠加不同的图形。
Scale修改坐标轴
scale_x_discrete("Cylinders"): x轴(的离散变量)名称为Cylinders
scale_y_continuous("Number", limits = c(-2,2)) :y轴(的连续变量)名称为Number,坐标轴从-2到2
scale_fill_manual("Transmission", values = c("#E41A1C", "#377EB8"), labels = c("Manual", "Automatic")):更改原图aes中fill的格式,图例名称为Transmission,颜色为"#E41A1C", "#377EB8",标签为"Manual", "Automatic"