Reputation: 23
I'm trying top prepare stacked bar chart with line chart and two y axis in R using plotly, but line part is not displaying. Both y axis are fine, stacked bar chart also works. Line chart by itself also works, but not together with stacked bar chart. When I tried it with only one y axis chart had all components, but because of different scale it's not visualizing data well enough. Here is code with sample data:
library(plotly)
#data
big <- c(300000,400000,500000,600000,500000,600000)
v1 <- c(3,4,5,5,4,3)
v2 <-c(3,4,5,5,4,3)
Date <- c("Jan 2016","Feb 2016","Mar 2016","Apr 2016","May 2016","June 2016")
df <- data.frame(big, v1, v2, Date)
#plot
p1 <- plot_ly(
x = df$Date,
y = df$big,
type="scatter"
)
p2 <- add_trace(
p1,
x = df$Date,
y = df$v2,
type = "bar",
yaxis="y2")
p25 <- add_trace(
p2,
x = df$Date,
y = df$v1,
type = "bar",
yaxis="y2"
)
p3 <- layout(p25,
xaxis = list(
title = "Month"
),
yaxis = list(
title = "big"
),
yaxis2=list(
title = "little",
tickfont = list(color = "red"),
overlying="y",
side="right"
),
barmode="stack"
)
p3
Any idea how to correct it?
Upvotes: 2
Views: 3380
Reputation: 2261
This worked for me:
# data
big <- c(300000,400000,500000,600000,500000,600000)
v1 <- c(3,4,5,5,4,3)
v2 <-c(3,4,5,5,4,3)
Date <- c("Jan 2016","Feb 2016","Mar 2016","Apr 2016","May 2016","June 2016")
df <- data.frame(big, v1, v2, Date)
library(plotly)
df %>%
plot_ly(x = ~Date) %>%
add_bars(y = ~v1,
name = "bar1") %>%
add_bars(y = ~v2,
name = "bar2") %>%
add_lines(y = ~big,
name = "line",
yaxis = "y2") %>%
layout(barmode = "stack",
yaxis2 = list(overlaying = "y",
side = "right"),
barmode = "stack")
Upvotes: 3