Search code examples
rbar-charthistogramintervals

Add incremental tick marks on the Y-axis in barplot() for R


I created a relative frequency histogram, but am trying to add minor tick marks on the y-axis. When I use the axis() function as in the following code:

```displacement_hist <- barplot(table(dissertation$displaced)/nrow(dissertation),
    axis(2, at=seq(0, 5, .25)),
    main = "Global Displacement", #Give your chart a title
    xlab = "Displacement by Numbers", #Label the x axis
    las = 2,
    cex.lab=.75,
    cex.axis =.75,
    cex.names = .75,
    ylab = "Relative Frequency")```

it produces this image: My histogram. When I use the same code with ylim as follows:

```displacement_hist <- barplot(table(dissertation$displaced)/nrow(dissertation),
    axis(2, at=seq(0, 5, .25)),
    ylim = c(0, .05),
    main = "Global Displacement", #Give your chart a title
    xlab = "Displacement by Numbers", #Label the x axis
    las = 2,
    cex.lab=.75,
    cex.axis =.75,
    cex.names = .75,
    ylab = "Relative Frequency")```

It produces this image: My histogram2. I would like the values for the tick marks on the y-axis to range from 0 to .05 with intervals of .0025. How can I do this? Thank you in advance.


Solution

  • Here is one way to get what you want. First we have to create some fake data that is similar to yours:

    set.seed(42)
    diss <- data.frame(displaced=sample(50, 200, replace=TRUE))
    displacement_hist <- barplot(table(diss$displaced)/nrow(diss), ylim=c(0, .05), 
        main = "Global Displacement", xlab = "Displacement by Numbers", 
        las = 2, cex.lab=.75, cex.axis =.75, cex.names = .75, ylab = "Relative Frequency")
    axis(2, seq(0, .05, by=.0025), labels=FALSE, tck=-.01)
    

    Bar Plot