統計分析與活動調查

# 安裝所需套件(如尚未安裝)
if (!require("ggplot2")) install.packages("ggplot2")
## 載入需要的套件:ggplot2
library(ggplot2)

# 數據準備
Statistic <- c(68, 85, 74, 88, 63, 78, 90, 80, 58, 63)
Math <- c(85, 91, 74, 100, 82, 84, 78, 100, 51, 70)

data_bar <- data.frame(
    name = c("娛樂休閒", "知識閱讀", "體育競技", "科學創新", "公益活動"),
    value = c(5, 4, 3, 2, 1)
)

data_pie <- c(52, 23, 10, 8, 7)
labels_pie <- c("娛樂休閒", "知識閱讀", "體育競技", "科學創新", "公益活動")

# 開啟畫布
par(mfrow = c(2, 2)) # 將畫布分成 2x2 格局

# 1. 散佈圖
plot(Statistic, Math,
     pch = 17,
     col = "red",
     xlab = "Statistic",
     ylab = "Math",
     main = "班級的統計與數學成績")

# 2. 直方圖
hist(Math,
     col = "lightblue",
     main = "數學成績分佈",
     xlab = "Math",
     ylab = "次數")

# 3. 橫向長條圖
# 使用 base R 圖形
barplot(data_bar$value,
        names.arg = data_bar$name,
        col = "steelblue",
        horiz = TRUE,
        main = "活動興趣調查",
        xlab = "喜好程度")

# 4. 圓餅圖
pie(data_pie,
    labels = labels_pie,
    col = rainbow(length(data_pie)),
    main = "活動興趣比例")