library(ggplot2)
data(diamonds)
ggplot(diamonds, aes(x = price)) +
# 绘制直方图
geom_histogram(
bins = 30, # 分箱数量
fill = "#69b3a2", # 填充颜色
color = "white", # 边框颜色
alpha = 0.8 # 透明度
) +
# 添加数值标签
geom_text(
stat = "bin", # 使用直方图分箱统计
aes(
label = after_stat(count), # 显示频数
y = after_stat(count) # Y轴位置为频数值
),
bins = 30, # 分箱数量与直方图一致
vjust = -0.5, # 垂直调整(负值向上移动)
size = 2, # 标签字体大小
color = "black" # 标签颜色
) +
# 扩展Y轴范围避免标签被截断
scale_y_continuous(expand = expansion(mult = c(0, 0.1))) +
# 标题和标签
labs(
title = "钻石价格分布直方图(带频数标签)",
x = "价格(美元)",
y = "频数"
) +
theme_minimal()
#添加对数变换(解决右偏分布)
ggplot(diamonds, aes(x = price)) +
geom_histogram(fill = "steelblue", bins = 50) +
scale_x_log10(labels = scales::dollar) + # 对价格取对数
labs(title = "价格分布(对数尺度)")