I am creating a times series using ggplot2 in R. I would like to know how to show tick marks in the x-axis only for the months that are labeled (e.g. Mar 07, Mar 08, etc) while keeping the vertical grey lines for every single month.
The main reason is because having a tick mark for every month makes it hard to know which one correspond to the labels.
Here is an example of a plot:
Here is the line of R behind:
ggplot(timeseries_plot_data_mean,aes(as.numeric(project_date)))+
geom_line(aes(y=num_views))+geom_point(aes(y=num_views))+
stat_smooth(aes(y=num_views),method="lm")+
scale_x_continuous(breaks = xscale$breaks, labels = xscale$labels)+
opts(title="Monthly average num views")+xlab("months")+ylab("num views")
This is what would like to generate. See how the ticks are positioned right above the month label and the vertical lines are still there showing each month.
I manually edited the plot above using Inkscape, (ignore the q's, Inkscape strangely replaced the dots for q's)
One way to add minor ticks all around the border is to use the annotation_ticks() function in ggprism .
To set labels for X and Y axes in R plot, call plot() function and along with the data to be plot, pass required string values for the X and Y axes labels to the “xlab” and “ylab” parameters respectively. By default X-axis label is set to “x”, and Y-axis label is set to “y”.
Here is a solution using the minor_breaks
parameter of scale_x_date()
. To use this, your x-values must be of class Date
instead of numeric
.
library(ggplot2)
set.seed(123)
x <- seq(as.Date("2007/3/1"), as.Date("2012/4/1"), by = "1 month")
y <- ((exp(-10 * seq(from=0, to=1, length.out=length(x))) * 120) +
runif(length(x), min=-10, max=10))
dat <- data.frame(Months=x, Views=y)
x_breaks <- seq(as.Date("2007/3/1"), as.Date("2012/4/1"), by="1 year")
x_labels <- as.character(x_breaks, format="%h-%y")
plot_1 <- ggplot(dat, aes(x=Months, y=Views)) +
theme_bw() +
geom_line() +
geom_point() +
scale_x_date(breaks=x_breaks, labels=x_labels, minor_breaks=dat$Months)
png("plot_1.png", width=600, height=240)
print(plot_1)
dev.off()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With