Reputation: 55
I'd love to make a timeline density graph like the New York Times does for COVID-19 cases (screenshot below). I am trying to do it with crime data instead of COVID data. Any ideas on how to use R (ggplot2, plotly, etc) to make a graph like this that shows density by day? So far, I haven't found a similar style in the R-graph Gallery. Thanks.
update: Here is the closest approximation I have come up with so far:
dat_c_grp <- dat_c %>%
group_by(report_date, month) %>%
summarize(count = n())
p <- ggplot(dat_c_grp, aes(report_date, month, fill = count))+
geom_tile(color= "white",size=0.1) +
scale_fill_viridis(name="Daily",option ="C")
output:
I'd like the months collapsed the months into one row. I can't figure out how to make it all one row.
Upvotes: 1
Views: 376
Reputation: 55
Thanks to both Allan Cameron and Konrad Rudolph.
Here is the code to answer my question:
dat_c_grp <- dat_c %>%
count(report_date, month, name = 'count')
p <- ggplot(dat_c_grp, aes(report_date, 0, fill = count))+
geom_tile(color= "white",size=0.1) +
scale_fill_gradientn(colors = c("#f3df8e", "#fdad45", "#ff700a", "#cc0a06"))+
removeGrid()+
theme(panel.spacing = unit(50, "points"),
legend.position = "top",
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y=element_blank(),
strip.text = element_blank(),
panel.grid = element_blank())
p
And output:
Upvotes: 1
Reputation: 174476
Here's a full reprex of one way to do this which emulates the look of the original fairly well (obviously I've had to make the data up):
library(ggplot2)
set.seed(1)
Dates <- rep(seq(as.Date("2020-03-01"), by = "1 week", length.out = 36), 3)
Places <- rep(c("Conneticut", "Fairfield", "New Haven"), each = 36)
Cases <- as.numeric(replicate(3, rpois(36, dgamma((1:36)/3, 2.5) * 100))) +
as.numeric(replicate(3, rpois(36, 0.0002 * exp(1:36)^(1/3))))
df <- data.frame(Dates, Places, Cases)
ggplot(df, aes(Dates, Places, fill = Cases)) +
geom_tile(color = "gray92") +
facet_grid(Places~., scales = "free_y") +
scale_fill_gradientn(colors = c("#f3df8e", "#fdad45", "#ff700a", "#cc0a06")) +
theme_minimal() +
scale_x_date(date_breaks = "month", labels = scales::date_format("%b")) +
theme(panel.spacing = unit(50, "points"),
legend.position = "top",
axis.title.y = element_blank(),
strip.text = element_blank(),
panel.grid = element_blank())
Upvotes: 2