R ggplot2:设置额外的特定轴刻度标记

3

我有一个ggplot:

ggplot()+geom_line(data = data.frame(y = c(1,2,3), x=c(1,2,3)), aes(y=y,x=x))

在这里输入图片描述 我希望保留默认的轴刻度和标签(在我的程序中,我事先不知道图表的限制)。

在x = 1.5处,我想要添加一个额外的x轴刻度,标签为“hi”。

我知道scale_x_continuous(),但我不知道如何访问“转换对象计算的默认刻度”。

1个回答

7

ggplot2 使用基础函数 pretty(通过 scales::pretty_breaks 间接使用)来处理非转换轴。您可以善加利用:

df <- data.frame(y = c(1,2,3), x=c(1,2,3))

ggplot(df, aes(x, y)) + 
  geom_line() +
  scale_x_continuous(breaks = c(pretty(df$x), 1.5), labels = c(pretty(df$x), 'hi'))

在1.5版本中,它当然会重叠(您写的是“additional”,而不是“replace”,所以我不确定您想要什么)。如果您不想要这样,您需要做类似以下的操作:

pretty_br <- pretty(df$x)[abs(pretty(df$x) - 1.5) > 0.25]
ggplot(df, aes(x, y)) + 
  geom_line() +
  scale_x_continuous(breaks = c(pretty_br, 1.5), labels = c(pretty_br, 'hi'))

enter image description here


我指的是“替换”如果已经有标签,否则添加。因此第二个选项可以。 (可能应该更清楚!)谢谢! - PascalIv
你如何使用具有多个面板的绘图来完成这个任务? - Nikos Bosse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接