我在 ggplot 中有一条水平线,我想在 y 轴上标记它的值(7.1)。
library(ggplot2)
df <- data.frame(y=c(1:10),x=c(1:10))
h <- 7.1
plot1 <- ggplot(df, aes(x=x,y=y)) + geom_point()
plot2 <- plot1+ geom_hline(aes(yintercept=h))
谢谢您的帮助。
我在 ggplot 中有一条水平线,我想在 y 轴上标记它的值(7.1)。
library(ggplot2)
df <- data.frame(y=c(1:10),x=c(1:10))
h <- 7.1
plot1 <- ggplot(df, aes(x=x,y=y)) + geom_point()
plot2 <- plot1+ geom_hline(aes(yintercept=h))
谢谢您的帮助。
不清楚你想要7.1成为y轴的一部分,还是只需要给线条添加标签。假设你想要前者,你可以使用scale_y_continuous()
来定义自己的间断点。下面的代码可能能够实现你想要的效果(很可能需要微调):
plot1+ geom_hline(aes(yintercept=h)) +
scale_y_continuous(breaks = sort(c(seq(min(df$y), max(df$y), length.out=5), h)))
plot1 + geom_hline(aes(yintercept=h)) +
geom_text(aes(0,h,label = h, vjust = -1))
与Chase的解决方案类似,但使用现有标签进行更改。
ggplot_build(plot1)$layout$panel_ranges[[1]]$y.major_source
可用于提取现有标签并添加新标签h
。
plot1 + geom_hline(aes(yintercept=h)) +
scale_y_continuous(breaks = sort(c(ggplot_build(plot1)$layout$panel_ranges[[1]]$y.major_source, h)))
plot1 + geom_hline(aes(yintercept=h), colour="#BB0000", linetype="dashed") +
geom_text(aes( 0, h, label = h, vjust = -1), size = 3)
plot1
的现有标签,您必须使用:ggplot_build(plot1)$layout$panel_params[[1]]$y.major
这仅适用于线性坐标轴!如果您有一个非线性的y轴(例如对数),那么ggplot2会将刻度线在线性轴上的位置存储在$y.major
中。实际的刻度线标签存储为字符向量在$y.labels
中。因此,对于非线性y轴,您需要使用:
as.numeric(ggplot_build(cl.plot.log)$layout$panel_params[[1]]$y.labels)