#查看數據summary(iris)Sepal.Length Sepal.Width Petal.Length Petal.Width Species Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 setosa :50 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 versicolor:50 Median :5.800 Median :3.000 Median :4.350 Median :1.300 virginica :50 Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800 Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500接下來使用點圖呈現Sepal.Length的分布。
#載入ggplot2library(ggplot2)#基礎版本的點圖ggplot(iris, aes(Sepal.Length)) + geom_dotplot()了解不同組別中(Species)Sepal.Length的分布情況。
#呈現不同組別ggplot(iris, aes(Species, Sepal.Length)) + geom_dotplot(binaxis = "y", binwidth = 0.1, stackdir = "center")1. 第三行:geom_dotplot()是新的一個幾何元素。2. 第三行:binaxis = "y" 要求R根據y軸上的數據畫出點的分布圖。stackdir = "center" 使點的分布呈中心型,即兩邊對稱。
修飾背景的顏色和點的顏色。
#修改顏色ggplot(iris, aes(Species, Sepal.Length)) + geom_dotplot(binaxis = "y", binwidth = 0.1, stackdir = "center", colour = "black", fill = "steelblue", alpha = 0.5) + theme_bw()
將點圖與箱形圖結合在一起。
#添加箱形圖的幾何元素ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot(width = 0.5) + geom_dotplot(binaxis = "y", binwidth = 0.1, stackdir = "center", colour = "black", fill = "steelblue", alpha = 0.5) + theme_bw()
#與小提琴結合ggplot(iris, aes(Species, Sepal.Length)) + geom_violin() + geom_dotplot(binaxis = "y", binwidth = 0.1, stackdir = "center", colour = "black", fill = "steelblue", alpha = 0.5) + theme_bw()它可以將多個不同的幾何元素按照你的想法結合在一起,從而畫出信息量更大的圖。
讓R語言和統計變得簡單!