将点分配给 x 轴上的特定范围

Assign points to a specific range on x-axis

我用 ggplot2 生成了这张图,(我手动添加了红色矩形)

我想以某种方式“标记”x 轴间隔。

例如;从 1.45e+08。到 1.46e+08 被命名为“low”,1.46e+08。到 1.47e+08 作为“中间”,我只想在 x 轴上显示这个标签而不是值。

我有 label/interval 它所属的每个点的列表,如果有用的话,还有该范围的起始点和结束点的间隔。

我在生成图表时使用了这段代码

ggplot(erpeaks, aes(x=pos, y=score), position=position_jitter(w=0,h=0)) + 
  geom_point(stat = "identity", width=0.5, aes(colour = factor(label)))  +
  theme(plot.title=element_text(hjust=0.5))

我试图添加这个,但他只适用于确定间隔

 coord_cartesian(xlim = c(144018895.5,146957774.5))

还有这个,但这没有给出结果。

scale_x_discrete(c(144018895.5,146957774.5),labels = c("low")) 

谢谢。

您可以使用 facet_grid() 中的 cut() 功能来显示某些方面的某些 invervals。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.1

ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point() +
  facet_grid(~ cut(Sepal.Width, c(-Inf, 2.75, 3.75, Inf)),
             scales = "free_x", space = "free_x")

如果你想分配不同的标签,你可以预先重新标记剪辑。

df <- iris
df$facet <- cut(df$Sepal.Width, c(-Inf, 2.75, 3.75, Inf))
levels(df$facet) <- c("low", "medium", "high")

ggplot(df, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point() +
  facet_grid(~ facet,
             scales = "free_x", space = "free_x")

reprex package (v2.0.1)

于 2021-11-30 创建