Created
January 9, 2022 04:51
-
-
Save RamiKrispin/ee278aecfad008ce0beaddebaef9eb58 to your computer and use it in GitHub Desktop.
Creating waterfall chart with plotly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(plotly) | |
df <- data.frame(y = c(21, 44, 27, 8), | |
x = c(100, 200, 150, 250)) | |
df$x_cum <- cumsum(df$x) | |
df$y_cum <- cumsum(df$y) | |
df | |
p <- plot_ly() | |
shape_color <- "gray" | |
shapes <- list() | |
for(i in 1:nrow(df)){ | |
shapes[[i]] <- list(type = "rect", | |
fillcolor = shape_color, | |
line = list(color = shape_color), opacity = 0.7, | |
x0 = df$x_cum[i] - df$x[i] , x1 = df$x_cum[i], xref = "x", | |
y0 = df$y_cum[i] - df$y[i], y1 = df$y_cum[i], yref = "y") | |
} | |
p <- plot_ly() %>% | |
layout(title = "My title", | |
shapes = shapes, | |
yaxis = list(title = "Proportions (%)"), | |
xaxis = list(title = "X axis", showgrid = FALSE), | |
margin = list(t = 60, b = 60)) | |
for(i in 1:nrow(df)){ | |
if(i < nrow(df)){ | |
p <- p %>% add_segments(x = df$x_cum[[i]], | |
xend = df$x_cum[[i]], | |
y = 0, | |
yend = 100, | |
line = list(width = 4), | |
showlegend = FALSE) | |
} | |
p <- p %>% | |
add_annotations(text = paste(df$y[i], "%", sep = ""), | |
x = (df$x_cum[i] - df$x[i] / 2), | |
y = (df$y_cum[i] - df$y[i] / 2), | |
xref = "x", | |
yref = "y", | |
showarrow = FALSE) | |
} | |
p | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment