ggplot2第二个轴,在日志转换后带有自定义标签

时间:2018-04-10 03:48:16

标签: r ggplot2

下面的图表的第二个x轴带有自定义标签。

dat <- data.frame(f=seq(0.01,0.5,by=0.01),y=rnorm(50))
fPretty <- pretty(dat$f)
pPretty <- round(1 / fPretty, 2)

p1 <- ggplot(data=dat, aes(x=f,y=y))
p1 <- p1 + geom_line(color="red")
p1 <- p1 + labs(x = "Frequency")
p1 <- p1 + scale_x_continuous(expand = c(0,0),
                              sec.axis=sec_axis(~., breaks=fPretty,
                                                labels = pPretty,
                                                name="Period (1/f)"))
p1

我想将x轴转换为log10比例并绘制第二个轴以匹配:

p2 <- ggplot(data=dat, aes(x=f,y=y))
p2 <- p2 + geom_line(color="red")
p2 <- p2 + labs(x = "Frequency")
p2 <- p2 + scale_x_continuous(expand = c(0,0), trans="log10",
                              sec.axis=sec_axis(~., breaks=fPretty,
                                                labels = pPretty,
                                                name="Period (1/f)"))
p2

如何在fPretty中设置pPrettyp2以产生相同的效果?

即,在这种情况下:

fPretty <- c(0.01, 0.1)
pPretty <- round(1 / fPretty, 2)

我是否使用scales::log_breaks()scales::trans_format()

目的是为两个x轴指定自定义刻度线。

1 个答案:

答案 0 :(得分:0)

您必须在主x轴和第二个上指定刻度线位置。 这是在breaks中为主x轴添加scale_x_continuous

例如,

fPretty <- c(0.01, 0.1)
pPretty <- round(1 / fPretty, 2)

p2 <- ggplot(data=dat, aes(x=f,y=y))
p2 <- p2 + geom_line(color="red")
p2 <- p2 + labs(x = "Frequency")
p2 <- p2 + scale_x_continuous(breaks = fPretty, 
                expand = c(0,0), trans="log10",
                sec.axis=sec_axis(~., breaks=fPretty,
                                      labels = pPretty,
                                       name="Period (1/f)"))
p2

enter image description here

修改 使用fPretty中使用的pPrettyp1

p2&lt; - p2 + scale_x_continuous(break = fPretty,                               expand = c(0,0),trans =“log10”,                               sec.axis = sec_axis(〜。,breaks = fPretty,                                                 labels = pPretty,                                                 name =“Period(1 / f)”))

enter image description here