ggplot精确轴范围

brb*_*brb 0 r ggplot2

如何将轴范围设置为与指定完全相同?

对于以下示例,我希望 x 轴在 0% 处交叉(而不是如图所示的 -0.5%),并且我希望顶部值为 12%(而不是 12.5%)

我都尝试过:

scale_x_continuous(limits = c(0, 0.12))
Run Code Online (Sandbox Code Playgroud)

coord_cartesian(ylim = c(0, 0.12)) 
Run Code Online (Sandbox Code Playgroud)

按照:

如何在 ggplot2 R 图中设置轴限制?

我可以精确限制 ggplot 轴范围吗?

示例代码:

myData = data.frame(x = c(0, 1, 2, 3, 4, 5),
                  y = c(0.05,0.06, 0.07, 0.08, 0.09, 0.09))


ggplot() +
  geom_step(data=myData, aes(x=x, y=y), color='orange', size=1) +
  xlab('') +
  ylab('') +
  scale_y_continuous(labels = scales::percent, limits=c(0,0.12))


ggplot() +
  geom_step(data=myData, aes(x=x, y=y), color='blue', size=1) +
  xlab('') +
  ylab('') +
  scale_y_continuous(labels = scales::percent) + 
  coord_cartesian(ylim = c(0,0.12))
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

Mat*_*ina 5

你在找吗expand

coord_cartesian(ylim = c(0,0.12), expand=0)
Run Code Online (Sandbox Code Playgroud)

或更好(见评论)

scale_y_continuous(labels = scales::percent,
 expand = expand_scale(),
 limits = c(0,0.12))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 或者 `scale_y_continuous(labels = scales::percent, Expand = Expand_scale(), Limits = c(0,0.12)`。 (2认同)