gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:21:37 24 4
gpt4 key购买 nike

我有一个散点图,其中 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))

scatter plot

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

我想在轴上添加双刻度,但没有 linetype看起来像一条双线。产品应该看起来像 this .我知道像 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')

solution

最佳答案

I was thinking of adding a double tick on the axis, but there is no linetype that looks like a double line.



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

例如:

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')



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

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

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")



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

关于r - 如何使用 ggplot2 在 y 轴截距(y 轴)上添加一个点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61348415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com