我正在尝试三个子图,这些子图在最大y轴上具有相同的高度。似乎默认情况下,R只会在偶数位上写入y轴刻度,但我希望子图的y轴具有相同的高度(因此在绘图和标题之间具有相同的边距),即使最大值也是如此y轴不同。
以下是我的代码:
df <- data.frame(mean.1 <- c(0.8, 0.7), sd.1 <- c(0.07, 0.1),
mean.2 <- c(14, 11), sd.2 <- c(5.2, 8.1),
mean.3 <- c(3.5, 5.5), sd.3 <- c(1.4, 0.3)
)
# Global setting
par(mfcol = c(1, 3),
mar = c(4, 4, 3, 2), tcl = -0.5, mgp = c(3, 1, 0),
oma = c(2, 2, 2, 2), las = 1
)
# Subplot 1
subplot.1 <- barplot(mean.1,
names.arg = c('A', 'B'),
main = 'Subplot 1',
ylab = 'Mean for subplot 1',
col = c('blue', 'red'),
border = NA,
ylim = c(0, (max(mean.1) + max(sd.1))*1.2)
)
# Error bars
arrows(subplot.1, mean.1 - sd.1, subplot.1, mean.1 + sd.1,
col = c('blue', 'red'),
length = 0.05, angle = 90,
code = 2
)
# Subplot 2
mean.2 <- c(14, 11)
sd.2 <- c(5.2, 8.1)
subplot.2 <- barplot(mean.2,
names.arg = c('A', 'B'),
main = 'Subplot 2',
ylab = 'Mean for subplot 2',
col = c('blue', 'red'),
border = NA,
ylim = c(0, (max(mean.2) + max(sd.2))*1.2)
)
# Error bars
arrows(subplot.2, mean.2 - sd.2, subplot.2, mean.2 + sd.2,
col = c('blue', 'red'),
length = 0.05, angle = 90,
code = 2
)
# Subplot 3
mean.3 <- c(3.5, 5.5)
sd.3 <- c(1.4, 0.3)
subplot.3 <- barplot(mean.3,
names.arg = c('A', 'B'),
main = 'Subplot 3',
ylab = 'Mean for subplot 3',
col = c('blue', 'red'),
border = NA,
ylim = c(0, (max(mean.3) + max(sd.3))*1.2)
)
# Error bars
arrows(subplot.3, mean.3 - sd.3, subplot.3, mean.3 + sd.3,
col = c('blue', 'red'),
length = 0.05, angle = 90,
code = 2
)
这是我目前得到的。
答案 0 :(得分:1)
你可以试试ggplot。首先,我使用dplyr
和tidyr
根据所需的ggplot格式转换数据。然后使用facet_wrap()
和scales = "free_y"
绘制数据以获得不同的y轴刻度。
library(tidyverse)
# The data
df = data.frame(mean.1 = c(0.8, 0.7), sd.1 = c(0.07, 0.1),
mean.2 = c(14, 11), sd.2 = c(5.2, 8.1),
mean.3 = c(3.5, 5.5), sd.3 = c(1.4, 0.3))
# Pipeline
library(tidyverse)
df %>% select(-starts_with("sd")) %>%
bind_cols(group=c("A","B")) %>%
gather(key, value, -group) %>%
bind_cols(sd=c(sd.1,sd.2,sd.3)) %>%
mutate(key=rep(paste("Subplot", 1:3), each = 2)) %>%
ggplot(aes(x=group, y=value, fill=group)) +
geom_bar(stat="identity") +
geom_errorbar(aes(ymin=value-sd, ymax=value+sd, col=group), width=0.1) +
theme_bw() + theme(legend.position="none") +
facet_wrap(~key, scales = "free_y")
使用base R我没有直接的解决方案。我建议使用ylim=c()
和axis()
函数,如果是小y轴,如下所示:
par(mfrow=c(1, 3))
barplot(df$mean.1, ylim=c(0, round(max(df$mean.1 + df$sd.1))))
barplot(df$mean.2, ylim=c(0, round(max(df$mean.2 + df$sd.2))), axes=F)
axis(2, at=c(0, seq(1, 20, 2)))
barplot(df$mean.3, ylim=c(0, round(max(df$mean.3 + df$sd.3))))