在ggplot2中为对数缩放的y轴添加等长的线段

时间:2018-07-16 17:28:51

标签: r ggplot2

对于以下数据

x <- c(1, 1.5, 1.8, 2)
y <- 10^x
data <- data.frame(x, y)

我想绘制对数y与x的关系,并为每个x轴值添加以y为中心的等长垂直刻度线。我尝试使用下面的代码

library(tidyverse)
ggplot(data, aes(x, y)) + geom_point() +
scale_y_continuous(limits = c(0.01, 10001),
                   trans = 'log10',
                   expand = c(0, 0)) + 
geom_segment(aes(x = 1.5, y = (10^1.5)-30, xend = 1.5, yend = (10^1.5)+30)) +
geom_segment(aes(x = 1.8, y = (10^1.8)-30, xend = 1.8, yend = (10^1.8)+30)) + 
geom_segment(aes(x = 2, y = (10^2)-30, xend = 2, yend = (10^2)+30))

结果图像如下: enter image description here

由于对数刻度,该图有两个问题: (1)y值点上下的垂直刻度的长度不同,这在x = 1.5时最明显。 (2)总垂直刻度线长度与x值不同(x = 1.5时最长)。

我希望绘制以y值为中心的垂直刻度线(该点上方和下方的刻度线长度相同),并且总长度(刻度线的最高极值和最低极值之间的垂直距离)与x不变轴值。

一种解决方案可能是做一些对数计算,但我坚持这样做。也许另一种选择是以厘米为单位添加垂直线段,以使刻度线的长度相等,而与y比例无关。但是我不知道cm的适当值是多少(除试错法外),并且还没有找到任何可直接用于此目的的函数。

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

len = 2
data$hi = exp(log(data$y) + len)
data$lo = exp(log(data$y) - len)


ggplot(data, aes(x, y)) +
  geom_point() +
  scale_y_continuous(limits = c(0.01, 10001),trans = 'log10', expand = c(0, 0)) + 
  geom_segment(aes(xend = x, yend = hi)) +
  geom_segment(aes(xend = x, yend = lo))

enter image description here