# 第 4 章 長條圖

``````d <- ggplot(mpg, aes(fl))
d + geom_bar()``````

`drv`不同而填上不同顏色

``````s <- ggplot(mpg, aes(fl, fill = drv))
s + geom_bar()``````

## 4.1 幾何位置(position)

`geom_bar(position="XXX")`其中XXX有以下選擇：

• dodge：躲避
• fill：填滿（標準化成同高度，呈現比重變化用）
• stack：疊上
``````s <- ggplot(mpg, aes(fl, fill = drv))
s + geom_bar(position = "dodge")``````

## 4.2 類別排序

``````mpg2<-mpg
mpg2\$drv %>% as.factor -> mpg2\$drv
mpg2\$drv %>% levels``````
``## [1] "4" "f" "r"``
``mpg2\$drv %>% ordered(levels=c("r","4","f")) -> mpg2\$drv``
``````s <- ggplot(mpg2, aes(fl, fill = drv))
s + geom_bar(position = "dodge")``````

## 4.3 縱軸安排

``````mpg2 %>% group_by(fl,drv) %>%
mutate(number=n()) %>%
ungroup %>%
select(fl,drv,number) -> mpg2.partial``````
• y軸必需使用自己算的結果。
• `stat="identity"`
``````ggplot(mpg2.partial)+
geom_bar(aes(x=fl,y=number,fill=drv),
position = "dodge",
stat="identity")``````

## 4.4 缺乏類別

``````mpg2.partial %>% add_row(fl=c("c","c","d"),
drv=c("r","4","r"),
number=c(0,0,0)) -> mpg2.partial``````
``````ggplot(mpg2.partial)+
geom_bar(aes(x=fl,y=number,fill=drv),
position = "dodge",
stat="identity")``````

### 4.4.1 轉軸

``````ggplot(mpg2.partial)+
geom_bar(aes(x=fl,y=number,fill=drv),
position = "dodge",
stat="identity") +
coord_flip()``````