在ggplotly上添加第二个Y轴 [英] Adding second Y axis on ggplotly

查看:228
本文介绍了在ggplotly上添加第二个Y轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用plotly和ggplot创建了以下数据框对象和图形

I have created the following dataframe object and graph using plotly and ggplot

library(ggplot2)
library(plotly)

rdate <- function(x,
              min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
              max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
              sort = TRUE) {          
  dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace=TRUE)
  if (sort == TRUE) {
    sort(dates)
  } else {
    dates
  }
}

DF<-data.frame(Date = rdate(100))
DF$variable<-LETTERS[seq( from = 1, to = 10 )]
DF$Value<-round(runif(1:nrow(DF),min = 10, max = 50))

接下来,我用ggplot创建了一个绘图对象

Next I have created a plot object with ggplot

 p <- ggplot(DF, aes(x = Date, y = Value, colour = variable)) + 
  geom_line() + 
  ylab(label="Sellcount") + 
  xlab("Sell Week")
  p<-p + scale_y_continuous(sec.axis = dup_axis())
  ggplotly(p)

如果我使用plot(p)绘制p,则该图有2个矢状点,正如我期望的那样.但是,当我使用ggplotly(p)绘制图形时,仅生成一个Y轴.我无法在互联网上找到与此相关的任何文献.我要求有人在这方面帮助我.

IF i plot p using plot(p), the graph has 2 yaxes as I expect. However, when I use ggplotly(p) to plot the graph, only one Y axis is generated. I am unable to find any literature on the internet regarding the same. I request someone to help me in this.

推荐答案

一个简单的解决方法是手动添加第二个轴:

A simple workaround is to add the second axis manually:

ay <- list(
  tickfont = list(size=11.7),
  titlefont=list(size=14.6),
  overlaying = "y",
  nticks = 5,
  side = "right",
  title = "Second y axis"
)

ggplotly(p) %>%
  add_lines(x=~Date, y=~Value, colors=NULL, yaxis="y2", 
            data=DF, showlegend=FALSE, inherit=FALSE) %>%
  layout(yaxis2 = ay)

这篇关于在ggplotly上添加第二个Y轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆