我试图用它们的 sd 值绘制一些值,但 sd 线不在每个条形图的中间。你知道如何解决或者是否有其他方法。
这是一个例子:
# Example data: Values and their standard deviations
values <- c(10, 15, 20, 25, 30) # Mean values
std_dev <- c(1, 2, 1.5, 3, 2.5) # Standard deviations
labels <- c("A", "B", "C", "D", "E") # Labels for each bar
# Create a bar plot with custom labels and error bars
barplot(values, ylim = c(0, max(values) + max(std_dev)),
names.arg = labels, xlab = "Groups", ylab = "Values",
main = "Example Bar Plot with Error Bars", cex.names = 0.7,
col = "skyblue", cex.axis = 1)
# Add error bars representing standard deviations
for (i in 1:length(values)) {
arrows(x0 = i, y0 = values[i] - std_dev[i],
x1 = i, y1 = values[i] + std_dev[i],
angle = 90, code = 3, length = 0.1)
}
barplot()
函数返回一个给出条形中心的向量。所以在你的代码中使用它:
# Create a bar plot with custom labels and error bars
centers <- barplot(values, ylim = c(0, max(values) + max(std_dev)),
names.arg = labels, xlab = "Groups", ylab = "Values",
main = "Example Bar Plot with Error Bars", cex.names = 0.7,
col = "skyblue", cex.axis = 1)
# Add error bars representing standard deviations
for (i in 1:length(values)) {
arrows(x0 = centers[i], y0 = values[i] - std_dev[i],
x1 = centers[i], y1 = values[i] + std_dev[i],
angle = 90, code = 3, length = 0.1)
}