I have implemented a density plot in R using ggplot2 (updated version):
library(ggplot2)
densityplot <- function(values, pointsInTime, title) {
df <- data.frame(x = 1:length(pointsInTime), y = values)
p <-
ggplot(df, aes(x = x, y = y)) +
geom_area(alpha = 0.5, fill = '#42a5ed') +
geom_line(color = '#42a5ed') +
geom_point(
color = '#42a5ed',
fill = 'white',
shape = 21,
size = 3
) +
scale_x_continuous(labels = pointsInTime, breaks = 1:length(df$x)) +
theme(
panel.background = element_blank(),
panel.grid.major.y = element_line(color = '#dddddd'),
panel.grid.major.x = element_blank(),
axis.text.x = element_text(margin = margin(10, 0, 0, 0)),
axis.text.y = element_text(margin = margin(0, 10, 0, 0)),
plot.title = element_text(size = 18),
axis.title = element_blank(),
axis.ticks = element_blank()
) +
coord_cartesian(expand = FALSE, xlim=min(df$x):max(df$x), ylim=0:max(df$y)+1) +
labs(title = title)
p
}
densityplot(sample(10:25, size = s),
format(ISOdate(2017, 1:12, 1), "%b"),
"Number of Fatal Accidents")
Update: Now the 'Dec' label on the bottom right is cut off. Is there a way to add margin or spacing?
Initial Problem: The horizontal grid lines in the background are too wide. I want them to just begin where the 'Jan' tick resp. to end where the 'Dec' tick would be; just covering the actual plot area, not the whole panel. However, I want to have the space around the panel to stay the same, i.e. the axis labels should not move towards the data.