如何使用 ggplot2 在 y 轴截距(y 轴)上添加一个点

J. *_*Lee 5 plot r data-visualization scatter-plot ggplot2

我有一个散点图,其中 y 轴缩放比例在某个点发生变化以绘制具有某些极值的数据。我正在尝试在 y 轴上添加某种视觉提示,指示缩放在该点发生变化。

这是一个情节的例子

library(scales)
library(ggplot2)

set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

transformation <- trans_new(
  "my_transformation", 
  transform = function(x) ifelse(x <= 30, x / 5, (x - 30) / 20 + 30 / 5),
  inverse = function(x) ifelse(x <= 30 / 5, x * 5, (x - 30 / 5) * 20 + 30)
)

ggplot(data = ggdata) + 
  geom_jitter(aes(x = x, y = y)) +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110))  
Run Code Online (Sandbox Code Playgroud)

散点图

我想在 y 轴上的“tick 30”上添加一些标记以进行比例更改。

我想在轴上添加双刻度线,但没有linetype看起来像双线。产品应该看起来像这样。我知道像 那样的转换scale_y_log10,但我更愿意使用随数据动态变化的自定义缩放。

编辑:根据@Tjebo 的建议,我曾经annotate在 y 轴断点上添加一个“=”:

library(scales)
library(ggplot2)

set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

transformation <- trans_new(
  "my_transformation", 
  transform = function(x) ifelse(x <= 30, x / 5, (x - 30) / 20 + 30 / 5),
  inverse = function(x) ifelse(x <= 30 / 5, x * 5, (x - 30 / 5) * 20 + 30)
)

mybreaks <- c(0, 10, 20, 30, 50, 70, 90, 110)
tick_linetype <- rep("solid", length(mybreaks))
tick_linetype[4] <- "blank"

ggplot(data = ggdata) + 
  geom_jitter(aes(x = x, y = y)) +
  annotate(geom = "point", shape = "=", x = -Inf, y = 30, size = 3) +
  scale_y_continuous(trans = transformation, breaks = mybreaks) +
  theme(axis.ticks.y = element_line(linetype = tick_linetype)) + 
  coord_cartesian(clip = 'off')
Run Code Online (Sandbox Code Playgroud)

解决方案

Tje*_*ebo 3

我正在考虑在轴上添加双勾,但没有看起来像双线的线型。

您可以使用任何字符作为点形状。还有等号、反斜杠等。

例如:

library(scales)
library(ggplot2)

set.seed(104)

ggdata <- data.frame('x' = rep('a',100),
                     'y' = c(runif(90, 0, 20), runif(10, 90, 100)))

transformation <- trans_new(
  "my_transformation", 
  transform = function(x) ifelse(x <= 30, x / 5, (x - 30) / 20 + 30 / 5),
  inverse = function(x) ifelse(x <= 30 / 5, x * 5, (x - 30 / 5) * 20 + 30)
)

ggplot(data = ggdata) + 
  geom_jitter(aes(x = x, y = y)) +
  annotate(geom = "point", shape = "=", x = -Inf, y = 30, size = 8, color = 'red') +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110))+
  coord_cartesian(clip = 'off')
Run Code Online (Sandbox Code Playgroud)

我删除了剪辑,但您也可以保留它。选择颜色只是为了突出显示。

或者,更好的是,使用文本注释。然后你还可以改变角度——这很好。

ggplot(data = ggdata) +
  geom_jitter(aes(x = x, y = y)) +
  annotate(geom = "text", label = "=", x = -Inf, y = 30, size = 8, color = "red", angle = 45) +
  scale_y_continuous(trans = transformation, breaks = c(0, 10, 20, 30, 50, 70, 90, 110)) +
  coord_cartesian(clip = "off")
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.3.0)于 2020-04-21 创建

  • 是的,谢谢!这是最接近我一直在寻找的东西。我不知道我可以将 `annotate()` 中的 `x` 设置为 `-Inf`,更不用说包含它不会改变整体的 x 比例。 (2认同)