用ggplot包畫一個簡單餅圖

首先用library函數加載ggplot2包數組

library(ggplot2)
library(dplyr)
library(tidyr)
library(splines)

接下來,進行數據準備:ide

df <- data.frame(
  var=LETTERS[1:3], 
id=1:3, a=c(0.25,0,35,0,4), stringsAsFactors = F #不轉換爲因子 )

咱們已經有了一個一維數組,而data.frame是將這個數組轉換爲二維,print的結果是這樣的: 函數

  var id rate
1   A  1 0.25
2   B  2 0.35
3   C  3 0.40

接下來,用一個函數畫餅圖:blog

ggplot(df,aes(x=factor(1),rate,fill=factor(var)))+
  geom_bar(stat="identity",position="fill")+
  coord_polar(theta="y")+ # 按Y軸極座標轉換
  labs(title="餅圖")

factor(1)指的是將x的值以相同的參數設定,這裏設爲factor(1)。string

用‘+’設置其餘參數,標題,變量名,比例等。it

stat='identity'是設置顏色,這裏是系統自有的顏色。io

最後效果如圖:class