test test - 1 year ago 100
R Question

Alternate x-axis labels within a plot

I am trying to obtain a plot where the in the x-axis should be the 12 months of the year from October to September.

The point is that I desire to have the x-axis labels displayed with alternate months and therefore only: Oct, Dec, Feb, Apr, Jun, Aug.

Here my data.frame and code which display all the months:

df_1 <- cbind.data.frame(
Var1 = c('Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'),
Freq = c(224, 1208, 1753, 1918, 1296, 1479, 389, 1433, 1300, 1621, 1222, 362)) #df = data_table

x1 = factor(df_1$Var1, levels = c('Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep'))

# Turn x1 factors into numeric values and
# plot as line plot without x-axis labels
plot(as.numeric(x1), df_1$Freq, type = 'l', yaxt = 'n', ylim = c(0, 1900),
xaxt = "n",
xlab = "Month",
ylab = "Count", main = 'All data', cex.lab = 2)

# Add custom x-axis with labels
# given by the levels of x1
axis(1, at = as.numeric(x1), labels = as.character(x1))
axis(2, at=seq(0, 1900, by=100))

If I replace x1 with:

x1 = factor(df_1$Var1, levels = c('Oct', '', 'Dec', '', 'Feb', '', 'Apr', '', 'Jun', '', 'Aug', ''))

The plot doesn't work anymore.

Any suggestion?


Answer Source

Use this:

axis(1, at = as.numeric(x1[seq(1, 12, 2)]), labels = as.character(x1[seq(1, 12, 2)]))


enter image description here


x1[seq(1, 12, 2)] will return the odd factors (the ones you want).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download