【问题标题】:ggplot, ggplotly, scale_y_continuous, ylim and percentageggplot、ggplotly、scale_y_continuous、ylim 和百分比
【发布时间】:2016-05-22 14:46:15
【问题描述】:

我想绘制一个 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()

现在我想将 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()

但结果与上图相同,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()

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

【问题讨论】:

  • 您可以将数据集添加到您的帖子中吗?

标签: r ggplot2


【解决方案1】:

我知道距离您提出要求已经有一段时间了,但您可以在 scale_y_continuous() 中使用 limits,如下所示:

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

【讨论】:

    【解决方案2】:

    建议对上述回复进行少量修改:

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

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

    【讨论】:

      【解决方案3】:

      由于您没有给出数据集,我正在做出最好的猜测。

      您需要在scale_y_continuous 中提供limits 选项。如您所见,ylim 不会覆盖scale_y_continuous 设置的美学。您需要使用一种功能来改变 y 轴的美观性。使用ylimscale_y_continuous

      【讨论】:

        【解决方案4】:

        我在这里遇到了类似的问题,两种解决方案都不适合我。很明显,我们不能将scale_y_continuousylim 结合起来。在scale_y_continuous 内设置限制参数会导致一些错误。但是,正如docs 中所建议的,我们可以将函数coord_cartesian()scale_y_continuous 结合使用。最终的代码是这样的:

        ...+
        coord_cartesian(ylim=c(0.50, 0.75)) +
        scale_y_continuous(labels = scales::percent)
        

        【讨论】:

          猜你喜欢
          • 2020-06-01
          • 2018-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-24
          • 1970-01-01
          • 2019-09-07
          相关资源
          最近更新 更多