jake9115
jake9115

Reputation: 4084

How to assign arbitrary x-axis value in R for a barplot?

I wish to make a barplot in R with 1000 vertical bars based on a list of numbers. Then, I want the resulting graph to have an x-axis that is labeled 1-10, evenly spaced underneath the 1000 columns. However, I only can figure out how to label every single column instead of the method I want. Here is my current code:

scores <- c(my 1000 data points)
barplot(scores, main="my plot", xlab="my 1000 scores", names.arg=c("list of 1-10"))

Does anyone know if it is possible to have the format of X-axis I desire? Thanks!

Upvotes: 1

Views: 1253

Answers (2)

Ed G
Ed G

Reputation: 822

You can do it by naming the 'scores' in the right places

scores <- sample(1000)
names(scores)<-NA
names(scores)[seq(1, 1000, 111)]<-1:10
barplot(scores, main="my plot", xlab="my 1000 scores")

How does this work?

We'll break down this line:

names(scores)[seq(1, 1000, 111)] <- 1:10

We've already assigned a name to every value in 'scores' (NA)

I can call those names with names(scores) and I can call subsets of those names with names(scores)[1:10]

Now for seq(1, 1000, 111) - this is a sequence from 1 to 1000 in steps of 111

So names(scores)[seq(1, 1000, 111)] is a subset of the names of 'scores' - specifically numbers 1, 112, 223 etc.

Why did i use 111? We are trying to space 10 values equally over 1000 'slots'. You calculate the steps with (1000 - 1) / (10 - 1)

For your second example (10 to 100 in steps of 10) we can simply replace <-1:10 with a different set of numbers seq(10, 100, 10)

Notice that length(1:10) and length(seq(10, 100, 10)) are both 10

Now for your final example length(seq(0, 100, 10))

By including 0, you have added an extra value (11 in total) so we need to use different slots in names(scores)

(1000 - 1)/(11-1) = 99.9 so we need to reset the names

names(scores) <- NA

then set the names with the new sequence

names(scores)[seq(1, 1000, 99.9)]<-seq(0, 100, 10)

Upvotes: 3

J&#246;rg M&#228;der
J&#246;rg M&#228;der

Reputation: 677

The x-Position of each bar is returned by the function itself. So just use xpos <- barplot(...). The y-Values you may calculate from par('usr')

or you use axis

tmp <- barplot(scores, main="my plot", xlab="my 1000 scores", names.arg=c(""))
axis(1,at=seq(min(tmp),max(tmp),len=10),lab=1:10)

Upvotes: 1

Related Questions