# Câu 1 (R)
## 1. Sinh ngẫu nhiên 600 giá trị từ phân phối nhị thức n = 20, p = 0.5
set.seed(123)
x <- rbinom(600, size = 20, prob = 0.5)
## 2. Vẽ histogram và so sánh với phân phối chuẩn (đường chuẩn dùng mean/sd của x)
library(ggplot2)
df <- data.frame(x = x)
ggplot(df, aes(x = x)) +
geom_histogram(aes(y = ..density..),
bins = 20,
fill = "lightblue",
color = "black") +
stat_function(fun = dnorm,
args = list(mean = mean(x), sd = sd(x)),
color = "red",
linewidth = 1) +
labs(title = "Histogram của mẫu rbinom(600,20,0.5) và đường chuẩn xấp xỉ",
x = "Giá trị", y = "Mật độ")
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# Câu 2 (Python)
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Đọc file csv vừa tạo từ R
iris = pd.read_csv("iris.csv")
# 1) Hiển thị bảng mean & std theo loài
# Thêm numeric_only=True để tránh cảnh báo trong các phiên bản Pandas mới
grouped = iris.groupby("Species").agg(["mean", "std"])
print(grouped)
## Sepal.Length Sepal.Width ... Petal.Length Petal.Width
## mean std mean ... std mean std
## Species ...
## setosa 5.006 0.352490 3.428 ... 0.173664 0.246 0.105386
## versicolor 5.936 0.516171 2.770 ... 0.469911 1.326 0.197753
## virginica 6.588 0.635880 2.974 ... 0.551895 2.026 0.274650
##
## [3 rows x 8 columns]
# 2) Vẽ boxplot cho Sepal.Width
plt.figure()
sns.boxplot(x="Species", y="Sepal.Width", data=iris)
plt.title("Boxplot Sepal.Width theo Species")
plt.xlabel("Species")
plt.ylabel("Sepal.Width")
plt.show()
