Set Date Range in Ggplot

set date range in ggplot

The documentation at ?scale_x_date mentions that it accepts all "typical" continuous scale arguments, including limits:

library(scales)
ggplot(z, aes(Month, Value)) +
geom_bar(fill="orange",size=.3, stat="identity", position="identity") +
geom_smooth(data=z,aes(Month,Value,group=1), method="lm", size=2, color="navyblue") +
scale_x_date(date_breaks = "1 month",
labels=date_format("%b-%Y"),
limits = as.Date(c('2011-01-01','2013-01-01')))

How to set date axis limits in ggplot2?

ggplot2 expands the axes. You can prevent the expansion of the x-axis by setting expand = c(0,0) in scale_x_date.

However this can undesirably cut the labels. Maybe a better option is to give the breaks by setting

breaks = seq(as.Date("01/03/2018", '%d/%m/%Y'), as.Date("01/01/2020", '%d/%m/%Y'), by = "month")

in scale_x_date, instead of date_breaks = "1 month".

Plot specific date range with ggplot2

Try subsetting the dataframe while feeding it to ggplot like this:

ggplot(data=mydf[which(mydf$Date>"2016-11-30"),],
aes(x=Date, y=variable1)) +
geom_point() +
stat_smooth(color = "blue", fill = "lightskyblue") +
theme(axis.title.x = element_blank()) +
ylab("") + xlab("")+
ggtitle("Variable 1 units") +
scale_x_date(date_breaks = "months",
date_labels = "%b%y") +
theme_hc()

How to add a date range to ggplot in Rshiny?

The issue is that you have not set any start and end dates for the date range and your apps does not take care of that. Hence an easy fix would be to simply set a default start and end date. Additionally IMHO I don't see any reason for an observeEvent. Instead I would suggest to use a reactive to filter your data based on user inputs, which could then be used for plotting:

library(tidyquant)
library(tidyverse)
library(shiny)
library(shinyWidgets)
library(shinythemes)
library(plotly)

ui <- fluidPage(
# Title
titlePanel("Stock Price Visualization and Forecasting"),
# Sidebar
sidebarLayout(
sidebarPanel(
width = 3,
pickerInput(
inputId = "stocks",
label = h4("Pick a stock"),
choices = tickers$symbol,
selected = tickers,
options = list(`actions-box` = TRUE),
multiple = T
),
# Date input
dateRangeInput("daterange", "Pick a Time Period",
# value = today(),
start = min(prices$date),
end = today(),
min = min(prices$date),
max = today()
)
),
# Plot results
mainPanel(
plotlyOutput("plot", height = 600)
)
)
)

server <- function(input, output, session) {
prices_filtered <- reactive({
req(input$stocks)
prices %>%
dplyr::filter(symbol %in% input$stocks) %>%
filter(date > input$daterange[1] & date <= input$daterange[2])
})

output$plot <- renderPlotly({
req(input$stocks)
g <- ggplot(prices_filtered(), aes(date, close, color = symbol)) +
geom_line(size = 1, alpha = 0.9) +
theme_minimal(base_size = 16) +
theme(
axis.title = element_blank(),
plot.background = element_rect(fill = "white"),
panel.background = element_rect(fill = "grey"),
panel.grid = element_blank(),
legend.text = element_text(colour = "black")
)
ggplotly(g)
})
}

shinyApp(ui, server)

Sample Image

ggplot: date axis. How to set limits?

Maybe this is what you are looking for. Via the limits you set the range of the data. However, you have to keep in mind that ggplot2 by default expands a continuous axis by 5 percent on each side. The amount of expansion can be set via the expand argument. Additionally, if you want a specific start and/or end age then I would suggest to set the breaks via the breaks arguement instead of using date_breaks:

library(lubridate)
library(ggplot2)
library(tibble)

set.seed(42)
tibble(
date = ymd("2019/12/31") + 1:366,
value = rnorm(1:366)) %>%
ggplot(aes(date, value)) +
geom_line() +
scale_x_date("Day", breaks = seq(ymd("2020/01/01"), ymd("2020/12/31"), by = "10 days"), date_labels = "%b %d",
limits = ymd(c("2020/01/01", "2020/12/31")),
expand = c(0, 0)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

Sample Image

create specific date range in ggplot2 ( scale_x_date)

If you know exactly where you want your break values to be, then just tell ggplot

plot1<- ggplot(test, aes(yr, y=value)) +
geom_line()+
scale_x_date(breaks = seq(as.Date("2010-01-01"), as.Date("2050-12-31"), by="5 years"),
labels=date_format("%Y")) +
scale_y_continuous(breaks=seq(-4,6, by=1))

Sample Image

limits argument in scale_x_date (ggplot) still produces dates outside data.frame range

That's normal, as the argument you look for is not limits but expand, as that's the one adding a little extra space left and right of the limits. You don't have to specify the limits at all, as the minimum and maximum are used by default.

So this code gives you the plot you're after:

ggplot(data=df, aes(x=date, y=value)) +
geom_line() +
scale_x_date(date_breaks = "day", expand = c(0,0)) +
theme(axis.text.x=element_text(angle=90, vjust = 0.5))

From the help page:

expand : A numeric vector of length two giving multiplicative and
additive expansion constants. These constants ensure that the data is
placed some distance away from the axes. The defaults are c(0.05, 0)
for continuous variables, and c(0, 0.6) for discrete variables.

This gives

Sample Image

R / ggplot2: Can't change scale limits with dates

As your x-axis is in a date format, you need to use scale_x_date to manipule your x axis:

library(ggplot2)
ggplot(mydata_sub, aes(x = x, y = y))+
geom_point()+
scale_x_date(limits = c(min(mydata$x), max(mydata$x)))

Sample Image



Related Topics



Leave a reply



Submit