我正在构建一个对数刻度的条形图:
library(ggplot2)
library(scales)
data <- matrix(c("2%","A", 0.00013, 4.94e-06, "6%", "A", 1.7e-05, 7.95e-06, "2%", "B", 3.1e-06, 1.50e-07, "6%", "B", 6.8e-07, 5.04e-07), ncol=4, byrow=TRUE)
data <- as.data.frame(data); colnames(data) = c("P", "variable", "value", "sd")
data$value <- as.numeric(as.character(data$value)); data$sd <- as.numeric(as.character(data$sd))
plot <- ggplot(data=data, aes(x=P, y=value, fill=variable)) + geom_bar(stat="identity", color = "black", size = 1, width = 0.5, position = position_dodge()) +
scale_x_discrete(limits=c("2%", "6%")) + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x)) +
geom_errorbar(aes(ymin=value, ymax=sd), size=1, width=0.25, position=position_dodge(0.5))
plot
然而,我的数据类型在我的领域通常有不同的表示。我需要创建相同的直方图,但条形图将从 x 轴的另一侧开始,就在 x 轴标签的上方,如下所示:
我知道这样表示并没有什么意义,但这就是我必须这样做的方式(因为我想表明 A 实际上比 B 做得更好,这可能并不明显第一张图上的第一眼)。也许使用 ggplot2 根本不可能,因为这不适合 ggplot2 的逻辑?
答案 0 :(得分:1)
如果您可以容忍警告,您可以使用 after_scale()
设置您正在绘制的矩形的 ymax
值。
但是,您需要仔细考虑您对 sd
变量所做的操作以及对该值进行对数转换意味着什么(尤其是在标准差时)。
library(ggplot2)
library(scales)
data <- matrix(c("2%","A", 0.00013, 4.94e-06, "6%", "A", 1.7e-05, 7.95e-06, "2%", "B", 3.1e-06, 1.50e-07, "6%", "B", 6.8e-07, 5.04e-07), ncol=4, byrow=TRUE)
data <- as.data.frame(data); colnames(data) = c("P", "variable", "value", "sd")
data$value <- as.numeric(as.character(data$value)); data$sd <- as.numeric(as.character(data$sd))
plot <- ggplot(data=data, aes(x=P, y=value, fill=variable)) +
geom_bar(stat="identity", color = "black", size = 1, width = 0.5, position = position_dodge(),
aes(ymax = after_scale(-Inf))) +
scale_x_discrete(limits=c("2%", "6%")) +
scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x)) +
geom_errorbar(aes(ymin=value, ymax=sd), size=1, width=0.25, position=position_dodge(0.5))
#> Warning: Ignoring unknown aesthetics: ymax
plot
由 reprex package (v0.3.0) 于 2021 年 1 月 5 日创建