R語言基礎(chǔ)
今天學(xué)習的主要內(nèi)容是R語言基礎(chǔ)设塔,主要是學(xué)習R 作圖的基礎(chǔ),參考了生信星球《R數(shù)據(jù)科學(xué)--詳解ggplot2》一文圆凰。讓我們開始今天的學(xué)習吧!R 語言搞起体箕!
一专钉、mpg數(shù)據(jù)框
mpg是ggplot2的內(nèi)置數(shù)據(jù)框。我個人認為這些內(nèi)置的數(shù)據(jù)都是供我們初學(xué)者來練習代碼以及熟悉操作的累铅。
既然是ggplot2的內(nèi)置的跃须,那我們首先加載ggplot2這個R包。然后查看mpg的數(shù)據(jù)類型娃兽,行列情況菇民。我們發(fā)現(xiàn)mpg的數(shù)據(jù)類型為data.frame,即數(shù)據(jù)框投储。它是由234行和11列組成的第练。
library(ggplot2)
p <- mpg
class(p)
[1] "tbl_df" "tbl" "data.frame"
View(p)
如何查詢每列的非重復(fù)值及每個值的重復(fù)次數(shù)呢:用dplyr包的distinct函數(shù)。
library(dplyr)
distinct(p,manufacturer) #manufacturer替換為其他列名玛荞。僅顯示非重復(fù)值娇掏,不顯示重復(fù)次數(shù)。
count(p,manufacturer) #顯示出現(xiàn)次數(shù)
二勋眯、入門級繪圖模板
ggplot(data =) +
(mapping = aes())
三婴梧、圖形映射屬性
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy))
黑白不好看下梢,上色!H洹孽江!
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, color = class))
大小設(shè)置
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, size = class))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, size = class, color = class))
透明度和形狀
# 將車型class映射給透明度
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, alpha = class, color = class))
# 將車型class映射給形狀
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, shape = class, color = class))
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), color = "blue")
stroke-輪廓更改
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy, stroke = 3,color = class),shape=21)
三、圖像分面
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2) #分兩行展示
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
四番电、幾何對象竟坛,j簡單理解就是不同圖的類型
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy))
#分組
ggplot(data = mpg) +
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))
#隱式分組-線型
ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, linetype = drv),
)
#隱式分組-顏色
ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, color = drv),
show.legend = FALSE #不顯示圖例
)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy))
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
結(jié)語
跟著花花姐的教程來學(xué)習,真的棒钧舌!保姆級教程担汤,步步理解,對于我這小白很友善呀洼冻!