一條折線
library(gcookbook)
library(ggplot2)
ggplot(BOD, aes(x = Time, y = demand)) +
geom_line()
如果改成因子型變量,由於Time不包括6,X軸上也不會出現6,從5直接蹦到7。
ggplot(BOD, aes(x = factor(Time), y = demand, group = 1)) +
geom_line()
控制Y軸從0開始
ggplot(BOD, aes(x = Time, y = demand)) +
geom_line() +
ylim(0, max(BOD$demand))
設置不同的線性
ggplot(BOD, aes(x = Time, y = demand)) +
geom_line(linetype = 'dashed', size = 1, colour = 'blue')
點線圖
ggplot(BOD, aes(x = factor(Time), y = demand, group = 1)) +
geom_line() +
geom_point()
多條折線
library(plyr)
# 取由不同的supp和dose構成的每一組數據對應的len的平均值
tg <- ddply(ToothGrowth, c('supp', 'dose'), summarise, length = mean(len))
# 將顏色映射給supp
ggplot(tg, aes(x = dose, y = length, colour = supp)) +
geom_line()
# 將線型映射給supp
ggplot(tg, aes(x = dose, y = length, linetype = supp)) +
geom_line()
大約有如下類型
# 將形狀映射給supp
ggplot(tg, aes(x = dose, y = length, shape = supp)) +
geom_line() +
geom_point()
# 將填充色映射給supp7
ggplot(tg, aes(x = dose, y = length, fill = supp)) +
geom_line() +
# colour指的是邊框顏色,默認是黑色
geom_point(size = 4, shape = 21, colour = 'white')
當shape取NA時,不顯示點;當shape取單獨一個字母時,顯示爲那個字母;當shape取.時,顯示一個不隨size增大的小點;其他情況下shape的取值在0到25,分別對應不同形狀。
# 將數據標記點錯開
# 將填充色映射給supp7
ggplot(tg, aes(x = dose, y = length, fill = supp)) +
geom_line(position = position_dodge(0.1)) +
geom_point(size = 4, shape = 21, position = position_dodge(0.1), colour = 'white') +
# 手動設置顏色
scale_fill_manual(values = c('orange', 'lightgreen'))