Hello,
I am trying to create a shiny app for my colleagues to share some data on reported financial information of publicly traded companies. A small example of the data is reproduced below.
Data & Code:
library(shiny)
library(tidyverse)
data <- tibble(Qtr = as.Date(c("2018-02-01", "2018-05-01", "2018-08-01", "2018-11-01", "2019-02-01","2019-05-01","2019-08-01",
"2018-03-01", "2018-06-01", "2018-09-01", "2018-12-01", "2019-03-01", "2019-06-01", "2019-09-01")),
Ticker = c("NKE", "NKE", "NKE", "NKE", "NKE", "NKE", "NKE", "UAA", "UAA", "UAA", "UAA", "UAA", "UAA", "UAA"),
Revenue_YY = c(6.50, 12.80, 9.60, 9.50, 6.90, 4.00, 7.10,
5.80, 7.60, 2.40, 1.50, 1.60, 1.45, -0.90))
data
# ui
ui <- fluidPage(
selectInput("Ticker", "select Ticker", choices=c("NKE", "UAA"), selected="NKE"),
mainPanel(
plotOutput("Ticker_Chart")
)
)
# server
server <- function(input, output) {
output$Ticker_Chart <- renderPlot({
chart <- data %>%
filter(Ticker==input$Ticker) %>%
ggplot(aes(x=Qtr)) +
geom_line(aes(y=Revenue_YY), size=1) +
geom_hline(yintercept=0) +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
labs(y="Y/Y Change (%)", x="Quarter") +
ggtitle(paste0("Y/Y Revenue Trend: ", input$Ticker)) +
scale_x_date(date_breaks = "month", date_labels = "%b-%y")
chart
})
}
# Run the application
shinyApp(ui = ui, server = server)
The problem: I am struggling with customizing the tick marks on the x-axis using the date_breaks argument inside scale_x_date.
At the moment, I am using monthly ticks marks:
scale_x_date(date_breaks = "month", date_labels = "%b-%y")
But this is really not accurate, since the data here is in quarterly frequency. More importantly, the NKE data follows the Feb/May/Aug/Nov quarters, but the UAA data follows the Mar/Jun/Sep/Dec quarters.
I have tried using "3 months" as the date break, but that gives me weirdly out of sync axis ticks.
scale_x_date(date_breaks = "3 months", date_labels = "%b-%y")
What I need looks like this:
I defined two new vectors with the appropriate tick marks:
ticks_aug_qtr <- seq.Date(as.Date("2018-02-01"), to=as.Date("2019-08-01"), by="quarter")
ticks_sep_qtr <- seq.Date(as.Date("2018-03-01"), to=as.Date("2019-09-01"), by="quarter")
...and then included the appropriate vector inside scale_x_date using "breaks" argument.
scale_x_date(breaks = ticks_aug_qtr, date_labels = "%b-%y")
But I dont know how to dynamically change the breaks based on the selectInput Ticker choice.
Any help/guidance would be much appreciated.
Thanks!!