在 ggplotly 上添加第二个 Y 轴
Adding second Y axis on ggplotly
我使用 plotly 和 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
创建了一个绘图对象
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 个 yax 轴。但是,当我使用 ggplotly(p) 绘制图形时,只会生成一个 Y 轴。我无法在互联网上找到与此相关的任何文献。我请求有人帮助我。
一个简单的解决方法是手动添加第二个轴:
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)
我使用 plotly 和 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
创建了一个绘图对象 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 个 yax 轴。但是,当我使用 ggplotly(p) 绘制图形时,只会生成一个 Y 轴。我无法在互联网上找到与此相关的任何文献。我请求有人帮助我。
一个简单的解决方法是手动添加第二个轴:
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)