本文使用的数据集为diamonds,需要下面两行代码导入该数据集
library(ggplot2)
data("diamonds")
-
当对散点图添加拟合线的时候,
ggplot(iris, aes(Sepal.Length, Petal.Length))+
geom_point()+
geom_smooth(method = ‘loess’, se = F, color = ‘red’, size = 2, linetype = 6, alpha = 0.25)
但是当你想要透明的的线的时候此时无效,你可以这样:ggplot(iris, aes(Speal.Length, Petal.Length))+
geom_point()+
geom_line(stat = ‘smooth’, method = ‘lm’, se = F, color = ‘red’, size = 2, linetype = 6, alpha = 0.25)
-
关于添加注释或标签
ggplot(iris, aes(Speal.Length, Petal.Length))+
geom_point()+geom_text(aes(label = Species), check_overlap = TRUE)
或者+geom_text(aes(6, 7.5 ,label = ‘Scatter plot’))
或者+geom_label(es(6, 7.5 ,label = ‘Scatter plot’))
或者+annotate(‘text’, x = 6, y = 7.5, label = ‘Scatter plot’, color = ‘red’, fontface = ‘italic’) -
关于添加线的时候参数fill,他会把线于x轴的地方填满,给出一种面积的感觉,还可以添加透明度。这里给出绘制密度线的示例:ggplot(diamonds, aes(carat, color = cut, fill = cut))+geom_density(alpha = .5)。通过图形可以看出,透明度的时候可以很有效的观察数据。
-
直方图绘制出来都是黏在一起的,设定颜色可以有分开的感觉。ggplot(diamonds, aes(carat))+geom_histogram(fill = ‘steelblue’, color = ‘white’, bin = 40)
-
绘制条形图的时候,默认y轴是总量。ggplot(diamonds, aes(color, price, fill = color))+geom_bar(stat = ‘identity’)
-
若想要y轴为平均值,则:ggplot(diamonds, aes(color, price, fill = color))+geom_bar(stat = ‘summary’, fun.y = ‘mean’),但是尽量在数据预处理的时候就把这一步做完。
-
关于条形图中的堆叠图与非堆叠图。
ggplot(diamonds, aes(color, price, fill = cut))+
geom_bar(stat = ‘identity’, position=“stack”)其中参数position='dodge’为另一种效果。