How to properly plot a histogram with dates using ggplot?

I would like to create an interactive histogram with dates on the x-axis.
I have used ggplot+ggplotly.

I've read I need to use to pass the proper information using the "text=as.character(mydates)" option and sometimes "tooltips=mytext".

This trick works for other kinds of plots but there is a problem with the histograms, instead of getting a single bar with a single value I get many sub-bars stacked.
I guess the reason is passing "text=as.character(fechas)" produces many values instead of just the class value defining that bar.

How can I solve this problem?
I have tried filtering myself the data but I don't know how to make this the parameters match the parameters used by the histogram, such as where the dates start for each bar.

library(lubridate)
library(ggplot2)
library(plotly)

Ejemplo <- data.frame(fechas = dmy("1-1-20")+sample(1:100,100, replace=T),
            valores=runif(100))

dibujo <- ggplot(Ejemplo, aes(x=fechas, text=as.character(fechas))) +  
  theme_bw() +  geom_histogram(binwidth=7, fill="darkblue",color="black") +
  labs(x="Fecha", y="Nº casos") + 
  theme(axis.text.x=element_text(angle=60, hjust=1)) +
  scale_x_date(date_breaks = "weeks", date_labels = "%d-%m-%Y", 
  limits=c(dmy("1-1-20"), dmy("1-4-20"))) 

ggplotly(dibujo)
ggplotly(dibujo, tooltip = "text")

enter image description here

As you can see, the bars are not regular histogram bars but something complex.
Using just ggplot instead of ggplotly shows the same problem, though then you woulnd't need to use the extra "text" parameter.

Use as.Date() to create the date field/ column.

It's the same, both functions produce the same output, hence the same wrong plot.

Can you try using conventional date format: 2021-01-01?

Same problem.
At the end I will try with geom_bar and doing all the "binning" by hand.

I just noticed that you are converting the dates to text, that would explain the ordering issue.

Can you try it without: text=as.character(fechas))) ?

You had 2 errors. First, I removed the text command. Second, there is not package called ggplotly.

This is what you are looking for:

library(lubridate)
library(ggplot2)
library(plotly)

Ejemplo <- data.frame(fechas = dmy("1-1-20")+sample(1:100,100, replace=T),
                      valores=runif(100))

dibujo <- ggplot(Ejemplo, aes(x=fechas)) +  
  theme_bw() +  geom_histogram(binwidth=7, fill="darkblue",color="black") +
  labs(x="Fecha", y="Nº casos") + 
  theme(axis.text.x=element_text(angle=60, hjust=1)) +
  scale_x_date(date_breaks = "weeks", date_labels = "%d-%m-%Y", 
               limits=c(dmy("1-1-20"), dmy("1-4-20"))) 

plotly::ggplotly(dibujo)
ggplotly(dibujo, tooltip = "text")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.