Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell R's ggplot2 to put tick marks for some values of x-axis and still keep vertical lines for other values

Tags:

r

ggplot2

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:

See how ticks on the x-axis make it hard to know where is each month

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.

This is what would like to generate (Inkscape, image editor,strangely replaced the dots for q's

I manually edited the plot above using Inkscape, (ignore the q's, Inkscape strangely replaced the dots for q's)

like image 697
amh Avatar asked Jul 11 '12 19:07

amh


People also ask

How do I add a minor tick in ggplot2?

One way to add minor ticks all around the border is to use the annotation_ticks() function in ggprism .

How do you change the X axis labels in R?

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”.


1 Answers

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()

plot_1.png

like image 190
bdemarest Avatar answered Nov 03 '22 02:11

bdemarest