[R] Question about 'lables' & ect.

Marc Schwartz (via MN) mschwartz at mn.rr.com
Wed Mar 15 18:43:36 CET 2006

On Wed, 2006-03-15 at 17:54 +0100, jia ding wrote:
> Hi,
> I have a file named:
> test_R.txt
> aaa  2
> bbb  5
> ccc  7
> sss  3
> xxx  8
> I want to have a plot:
> test<-read.table("test_R.txt",col.name=c("Name","Score"))

> par(mfrow=c(1,2))

It's not clear what the purpose is here, at least in this example. Do
you plan on creating a second plot?

> barplot(test$Score)
> name<-test$Name
> axis(1,at=1:length(test$Name),labels=paste(name))
> Q1, if you try the script above,you will get 5 bars, the axis only shows
> "aaa", "ccc","xxx", but where are "bbb"&"sss"?

The easiest way to do this is to use the 'names.arg' argument in

barplot(test$Score, names.arg = as.character(test$Name))

Note that the 'Name' column in the 'test' data frame will be a factor by
default, so you need to convert it to a character vector here.

> Q2, pls have a look this x-axis again, you will find the middle of the bars
> are not pointing to the x-axes.

Note that in the Value section of ?barplot, it indicates that barplot()
returns the bar midpoints, which are not at integer values along the x

You would need to do something like:

mp <- barplot(test$Score)

axis(1, at = mp, labels = as.character(test$Name))

> Q3, how can i change the width of the bars? I feel they are too "fat".

You can use the 'space' argument:

barplot(test$Score, names.arg = as.character(test$Name), space = 0.5)

See the descriptions of the 'width' and 'space' arguments in ?barplot
for some of the subtleties here.

See ?barplot for more information and further examples.


Marc Schwartz

More information about the R-help mailing list