我刚开始使用 plotly,但在使用双 y 轴图时遇到了问题。我用两个在 ggplot 中生成了我的初始图形,但是当我通过 ggplotly() 运行它时只出现了一个。我一直无法弄清楚如何使用 layout() 添加一个。
我在 ggplot 中创建了一个双 y 轴图,但是当我用 ggplotly 绘制它时,它丢掉了第二个 y 轴。然后我尝试在他们的网站 (https://plotly.com/r/multiple-axes/) 上使用该技术,定义第二个标签,然后使用 layout() 附加它。它修改存在的标签,但不添加第二个 y 轴。关于如何实施这个的任何建议?下面的代码示例。
谢谢!
#packages
library(tidyverse)
library(plotly)
#Create functional double-y plot
dbly<-mtcars %>% ggplot(aes(x = disp)) +
geom_point(aes(y = hp), color = "red")+
geom_point(aes(y = mpg * 9), color = "blue")+
scale_y_continuous(name = "hp", sec.axis = sec_axis(~ . /9, name = "mpg"))
dbly
#Double-y plot loads both datasets but not both axes
egads<-ggplotly(dbly)
egads
#attempted to apply layout - second y axis, overwrites other
#labels but does not add second y
ay <- list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right",
title = "<b>secondary</b> yaxis title")
egads%>% layout(
title = "Double Y Axis Example", yaxis2 = ay,
xaxis = list(title="xaxis title "),
yaxis = list(title="<b>primary</b> yaxis title")
)
这是我们如何做到的:致谢
library(plotly)
# defining the attributes for the second y axis:
ay <- list(
tickfont = list(color = "red"),
overlaying = "y",
side = "right",
title = "hp"
)
plot_ly(mtcars, x = ~disp, y = ~hp, type = "scatter", mode = "markers", name='hp') %>%
add_trace(y = ~mpg, name = 'mpg', yaxis = "y2") %>%
layout(title = 'hp and mpg distribution',
yaxis = list(title = 'mpg'),
xaxis= list(title="disp"),
yaxis2 = ay)