How to make an R barplot with a log y-axis scale?

13,295

Solution 1

The log argument wants a one- or two-character string specifying which axes should be logarithmic. No, it doesn't make any sense for the x-axis of a barplot to be logarithmic, but this is a generic mechanism used by all of "base" graphics - see ?plot.default for details.

So what you want is

barplot(samples, log="y")

I can't help you with tick marks and labeling, I'm afraid, I threw over base graphics for ggplot years ago and never looked back.

Solution 2

This should get your started fiddling around with ggplot2.

d<-data.frame(samples)
ggplot(data=d, aes(x=factor(1:length(samples)),y=samples)) + 
    geom_bar(stat="identity") +
    scale_y_log10()

Within the scale_y_log10() function you can define breaks, labels, and more. Similarly, you can label the x-axis. For example

ggplot(data=d, aes(x=factor(1:length(samples)),y=samples)) +
    geom_bar(stat="identity") +
    scale_y_log10(breaks=c(1,5,10,50,100,500,1000),
                  labels=c(rep("label",7))) +
    scale_x_discrete(labels=samples)
Share:
13,295

Related videos on Youtube

jake9115
Author by

jake9115

Updated on June 18, 2022

Comments

  • jake9115
    jake9115 almost 2 years

    This should be a simple question... I'm just trying to make a barplot from a vector in R, but want the values to be shown on a log scale, with y-axis tick marks and labelling. I can make the normal barplot just fine, but when I try to use log or labelling, things go south.

    Here is my current code:

    samples <- c(10,2,5,1,2,2,10,20,150,23,250,2,1,500)
    barplot(samples)
    

    Ok, this works. Then I try to use the log="" function defined in the barplot manual, and it never works. Here are some stupid attempts I have tried:

    barplot(samples, log="yes")
    barplot(samples, log="TRUE")
    barplot(log=samples)
    

    Can someone please help me out here? Also, the labelling would be great too. Thanks!

  • jake9115
    jake9115 over 10 years
    Thanks for your help and explanation. This worked, and I'll look into ggplot as well.