Skip to content

Instantly share code, notes, and snippets.

@addiversitas
Created September 7, 2020 18:21
Show Gist options
  • Save addiversitas/c6d36bbc7656df3098e71a2f72ffdf9d to your computer and use it in GitHub Desktop.
Save addiversitas/c6d36bbc7656df3098e71a2f72ffdf9d to your computer and use it in GitHub Desktop.
end result after improving the plotly output
library("shiny")
library("plotly")
library("data.table")
dates <- seq(as.Date("2019-02-01"),length=12,by="months") - 1
books <- c(17,3,3,18,20,19,15,12,17,4,18,7)
laptops <- c(13,5,8,12,27,32,31,9,22,11,12,30)
tvs <- c(30,41,22,11,4,33,16,17,8,49,14,50)
data <- data.frame(dates = dates,
books = books,
laptops = laptops,
tvs = tvs)
data <- melt(data, id.vars = "dates")
data <- data %>%
group_by(variable) %>%
mutate(pct = value / sum(value), pct = scales::percent(pct))
server <- function(input, output) {
output$sales = renderPlotly({
fig <- plot_ly(data, x = ~dates, y = ~value, type = 'bar', name = ~variable, color = ~variable, text = ~pct, hovertemplate = "%{fullData.name} sold: %{y}<br>Percentage: %{text} <extra></extra>")
fig <- fig %>% layout(xaxis = list(tickvals = dates, tickformat = "%b %Y", tickfont = list(size = 12)), barmode = 'stack')
fig <- fig %>% config(modeBarButtons = list(list("toImage")), displaylogo = FALSE, toImageButtonOptions = list(filename = "plotOutput.png"))
fig <- fig %>% onRender("function(el, x) {Plotly.d3.select('.cursor-crosshair').style('cursor', 'default')}")
fig
})
}
ui <- fluidPage(
plotlyOutput("sales")
)
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment