7

I used barplot() function to create a stacked chart from matrix.

Matrix looks like this:

1 0.989013 0.010987
2 0.999990 0.000010
3 0.999990 0.000010
4 0.999990 0.000010

code to create a stacked chart looks like this:

barplot(t(as.matrix(x)), col=c("cyan", "black"))

The problem is that I want to create custom x axis with ticks and labels at certain points. I used following to create x axis:

axis(1, at=keyindexes, labels=unique(t$V4), tck=-0.01)

where keyindexes is vector of bar numbers where I need to have ticks and unique(t$V4) is vector containing unique name for each tick.

Now the problem is that x axis does not match with chart area and is significantly shorter. Can anyone advice on how to make x axis longer?

YKY
  • 2,493
  • 8
  • 21
  • 30

2 Answers2

19

The problem with axis labels is in fact that bars are not centered on whole numbers. For example, make some data with ten rows and plot them with barplot(). Then add axis() for x axis at numbers from 1 to 10.

set.seed(1)
x<-data.frame(v1=rnorm(10),v2=rnorm(10))
barplot(t(as.matrix(x)), col=c("cyan", "black"))
axis(1,at=1:10)

enter image description here

Now axis texts are not in right position.

To correct this problem, barplot() should be saved as object and this object should be used as at= values in axis.

m<-barplot(t(as.matrix(x)), col=c("cyan", "black"))
m
 [1]  0.7  1.9  3.1  4.3  5.5  6.7  7.9  9.1 10.3 11.5
axis(1, at=m,labels=1:10)

enter image description here

EDIT - plotting only some ticks

If only some of axis ticks texts should be plotted then you can subset m values that are needed and provided the same length of labels=. In this example only 1., 5. and 10. bars are annotated.

m<-barplot(t(as.matrix(x)), col=c("cyan", "black"))
lab<-c("A","B","C")
axis(1, at=m[c(1,5,10)],labels=lab)

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • thank you for your answer. The problem is that I need to show custom labels and ticks on X axis. That's why I gave a vector with sample/row number to _axis(at)_ parameter. I need ticks on 1, 15, 34, 38 and so on. 35 strictly specified ticks in total, across all 576 samples, gap between ticks vary greatly. So I can put a label with sample name on each tick, I used _label_ argument to specify label for each tick and gave it a vector with labels. Maybe there are other ways to do that instead of messing around with axis() function. – YKY Mar 11 '13 at 06:36
  • Maybe also this can help https://stackoverflow.com/questions/9981929/how-to-display-all-x-labels-in-r-barplot – Nisba Oct 13 '17 at 12:08
0

Look at the updateusr function in the TeachingDemos package. This function will change or "update" the user coordinates of a plot. The example shows changing the coordinates of the x axis of a barplot to match the intuitive values for additional plotting.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110