ggplot,ggplotly,scale_y_continuous,ylim和百分比

use*_*529 5 r ggplot2

我想绘制一个图表,其中y轴以百分比表示:

p = ggplot(test, aes(x=creation_date, y=value, color=type)) +
  geom_line(aes(group=type)) +
  scale_colour_manual(values=c("breach"="red","within_promise"="green","before_promise"="blue")) +
geom_vline(xintercept=c(as.numeric(as.Date('2016-05-14'))),linetype="dotted") + 
  scale_y_continuous(labels=percent)

ggplotly()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

现在,我想将y轴上限值设置为100%

p = ggplot(test, aes(x=creation_date, y=value, color=type)) +
  geom_line(aes(group=type)) +
  scale_colour_manual(values=c("breach"="red","within_promise"="green","before_promise"="blue")) +
geom_vline(xintercept=c(as.numeric(as.Date('2016-05-14'))),linetype="dotted") + 
  scale_y_continuous(labels=percent) +
  ylim(0, 1)

ggplotly()
Run Code Online (Sandbox Code Playgroud)

但是结果与之前的图相同,y轴限制相同。当我不将y轴设置为百分比时,它会起作用:

p = ggplot(test, aes(x=creation_date, y=value, color=type)) +
  geom_line(aes(group=type)) +
  scale_colour_manual(values=c("breach"="red","within_promise"="green","before_promise"="blue")) +
geom_vline(xintercept=c(as.numeric(as.Date('2016-05-14'))),linetype="dotted") + 
  ylim(0, 1)

ggplotly()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

此外,当我将y轴设置为百分比时,使用ggplotly时,将鼠标放在图形的一点上时,该值不是百分比:

在此处输入图片说明

dud*_*udu 6

自您提出要求以来,我知道这真是麻烦,但您可以像这样使用limitsinside scale_y_continuous()

scale_y_continuous(labels = scales::percent, limits=c(0,1))


小智 6

建议对上面的回复进行小修改:

看来您必须在将值设置为百分比之前scale_y_continuous调用中指定限制:

scale_y_continuous(limits=c(0,1), labels = scales::percent)


Div*_*ivi 2

由于您没有提供数据集,我正在做出我的最佳猜测。

您需要limits在 内给出选项scale_y_continuousylim正如你所看到的,并没有超越 所设定的美学scale_y_continuous。您需要使用一个函数来改变 y 轴的美观。使用ylimscale_y_continuous.