1. 繪製簡單條形圖ide
# 使用ggplot2和gcookbook library(ggplot2); library(gcookbook) g <- ggplot(data = pg_mean, aes(x = group, y = weight)) + geom_bar(stat = "identity", fill = "green", color = "black") # fill表示填充顏色,color表示邊線框顏色 g
2. 繪製簇狀條形圖spa
# 使用ggplot2和gcookbook的cabbage_exp數據集 library(ggplot2); library(gcookbook) g <- ggplot(data = cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar)) + # width表示每一個條形的寬度(默認是0.9, 當爲0.9時,能夠省略width = 0.9), position表示組內條形的間距(position = position_dodge(0.9)能夠替換成position = "dodge") #geom_bar(stat = "identity",width = 0.9, position = position_dodge(0.9)) # 上面和下面等價 geom_bar(stat = "identity", position = "dodge") g
3. 條形圖填充顏色3d
# 使用ggplot2和gcookboo的數據集upc library(ggplot2); library(gcookbook) upc <- subset(uspopchange, rank(Change) > 40) # 使用scale_fill_manual()對顏色進行填充 g <- ggplot(data = upc, aes(x = Abb, y = Change, fill = Region)) + geom_bar(stat = "identity") + scale_fill_manual(values = c("#5ED5D1", "#FF6E97")) g
4. 修改座標名稱、標題、添加數據標籤code
# 使用ggplot2和gcookbook的數據集cabbage library(ggplot2); library(gcookbook) # 添加標題、X軸、Y軸 # 方法1(經過ggtitle、xlab、ylab) g <- ggplot(data = cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) + geom_bar(stat = "identity") + ggtitle(label = "數據展現") + xlab(label = "日期, 品種") + ylab(label = "重量") + theme(plot.title = element_text(hjust = 0.5)) # 標題居中 g # ===================================== # 方法2(經過labs) g <- ggplot(data = cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) + geom_bar(stat = "identity") + labs(title = "數據展現", x = "日期, 品種", y = "重量") + theme(plot.title = element_text(hjust = 0.5)) # 標題居中 g # ===================================== # 添加數據標籤 g <- ggplot(data = cabbage_exp, aes(x = interaction(Date, Cultivar), y = Weight)) + geom_bar(stat = "identity") + labs(title = "數據展現", x = "日期, 品種", y = "重量") + theme(plot.title = element_text(hjust = 0.5)) + # 標題居中 geom_text(aes(label = Weight), vjust = 1.5) # 添加數據標籤,並設置位置 g