Black Lives Matter. Please consider donating to Black Girls Code today.

scale_x_date in ggplot2

How to make plots in R and ggplot2 using scale_x_date.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

By Month

library(plotly)
library(scales)

x <- c("04-01-10","05-01-10","06-01-10","07-01-10","08-01-10","09-01-10","10-01-10","11-01-10","12-01-10","01-01-11","02-01-11","03-01-11","04-01-11","05-01-11","06-01-11","07-01-11","08-01-11","09-01-11","10-01-11","11-01-11","12-01-11","01-01-12","02-01-12","03-01-12","04-01-12","05-01-12","06-01-12")
y <- c(120,210,130,160,190,210,80,70,110,120,140,160,130,200,110,180,210,200,90,60,100,100,120,170,100,180,120)

MySample <- data.frame(x) ## convert to dataframe
MySample$y <- y

# install.packages("lubridate")
require(lubridate)

MySample$date <- as.Date(MySample$x, "%m-%d-%y")
MySample$year <- year(MySample$date)

p <- ggplot(MySample, aes(date, y, fill = year)) +
    geom_bar(stat="identity") +
    facet_grid(. ~ year, scales = "free") +
    scale_x_date(labels = date_format("%b/%y")) +
    scale_fill_gradient(breaks=unique(MySample$year))

fig <- ggplotly(p)

fig

Inspired by Stack Overflow.

By Year

library(plotly)
library(scales)

set.seed(12345)
Date <- seq(as.Date("2010/1/1"), as.Date("2014/1/1"), "week")
Y <- rnorm(n=length(Date), mean=100, sd=1)
df <- data.frame(Date, Y)

df$Year <- format(df$Date, "%Y")
df$Month <- format(df$Date, "%b")
df$Day <- format(df$Date, "%d")

df$MonthDay <- format(df$Date, "%d-%b")

df$CommonDate <- as.Date(paste0("2000-",format(df$Date, "%j")), "%Y-%j")

p <- ggplot(data = df,
     mapping = aes(x = CommonDate, y = Y, shape = Year, colour = Year)) +
     geom_point() +
     geom_line() +
     facet_grid(facets = Year ~ .) +
     scale_x_date(labels = function(x) format(x, "%d-%b"))

fig <- ggplotly(p)

fig

Inspired by Stack Overflow.

What About Dash?

Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash for R at https://dashr.plot.ly/installation.

Everywhere in this page that you see fig, you can display the same figure in a Dash for R application by passing it to the figure argument of the Graph component from the built-in dashCoreComponents package like this:

library(plotly)

fig <- plot_ly() 
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... ) 

library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)

app <- Dash$new()
app$layout(
    htmlDiv(
        list(
            dccGraph(figure=fig) 
        )
     )
)

app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)