之前的文章介绍过各式各样的柱状图绘制:

1.柱状图添加误差线、置信区间等

2.R 绘制堆积柱状图

3.R 南丁格尔玫瑰图详细讲解

本文主要讲解如何定制你的柱状图,让其更加形象的展现你的数据,一个简单的示例:


# 演示数据
data <- data.frame(
    name = c(
        "A",
        "B",
        "C",
        "D" ,
        "A",
        "B",
        "C",
        "D" ,
        "A",
        "B",
        "C",
        "D"
    ),
    average = sample(seq(1, 10) , 12 , replace = T),
    number = sample(seq(4, 39) , 12 , replace = T)
)

# 定义画布
par(mar = c(6, 4, 4, 4))


# 绘制柱状图
my_bar <- barplot(
    data$average ,
    border = F ,
    # 定义分组
    names.arg = c("", "Group1", "", "", "", "Group2", "", "", "", "Group3", "", "") ,
    las = 1 ,
    axes = T,
    col = c(
        rgb(0.3, 0.1, 0.4, 0.6) ,
        rgb(0.3, 0.5, 0.4, 0.6) ,
        rgb(0.3, 0.9, 0.4, 0.6) ,
        rgb(0.3, 0.3, 0.5, 0.9)
    ) ,
    ylim = c(0, 13) ,
    main = ""
)

# 添加分割线
abline(v = c(4.9 , 9.7) , col = "grey")

# 添加标注文本
text(my_bar,
     # 文本相对位置
     data$average + 0.8 ,
     paste("n: ", data$number, sep = "") ,
     cex = 1)


# 添加图例
legend(
    0.1,13,
    legend = c("A", "B", "C", "D") ,
    col = c(
        rgb(0.3, 0.1, 0.4, 0.6) ,
        rgb(0.3, 0.5, 0.4, 0.6) ,
        rgb(0.3, 0.9, 0.4, 0.6) ,
        rgb(0.3, 0.3, 0.5, 0.9)
    ) ,
    bty = "n",
    pch = 20 ,
    pt.cex = 2,
    cex = 0.8,
    horiz = T,
    inset = c(0.05, 0.05)
)

最终结果如下:

参考资料:

1.https://www.r-graph-gallery.com/all-graphs.html