[R] Barplot difficulties

Marc Schwartz MSchwartz at MedAnalytics.com
Tue Nov 16 03:01:56 CET 2004

On Mon, 2004-11-15 at 19:03 -0500, Heather J. Branton wrote:
> Hello. I am an R newbie struggling to learn and use R . I have read many 
> portions of the R Reference Manual, as well as the FAQs. Given that I 
> learn something new each time, I know I might be missing something 
> obvious. But I appeal to your good nature to help me through this 
> initial problem.
> I have attached a pdf file to demonstrate what I desire and have listed 
> what my data looks like in Excel (below). Following is the data and 
> script I developed - which does not provide what I want.
> My immediate goal is to create a barplot in R similar to the attached 
> pdf chart. But I am stuck on several problems. First, I would like to 
> have 2 labels below the barplot - one label for each bar and one for 
> each group of bars. Second, I would like to vary color by group (instead 
> of by bar). I assume that I need to do use some sort of syntax within 
> the color option but have not yet figured it out. I have made two 
> different plot attempts -- one resulting in the bars being grouped 
> appropriately but missing the labels below the x-axis; the other giving 
> me the individual labels but not grouped as I need.


How about something like this:

# Don't use 'sample' for the name here, as sample() is a function
MyData <- t(read.table("sample.dat", sep= "," , header = TRUE))

# These may be closer to the PDF chart colors
# You need to repeat them to color each group the same, rather
# than alternating bar colors
MyCols <- rep(c("lightcyan","cornsilk","lavender"), each = 10)

# adjust the margins
par(mar = c(7, 5, 6, 4))

# Now do the barplot:
# Note barplot() returns the bar midpoints in 'mp'
# use 'names.arg' for the individual bar names from MyData
# set 'las = 2' for vertical labels
# set 'ylim' to c(0, 20) for the y axis range
# set 'yaxt = "n"' to not draw the y axis tick marks
mp <- barplot(MyData, beside = TRUE, col = MyCols, 
              main = "Rate by Group and Year", 
              ylab = "Rate", 
              names.arg = rep(rownames(MyData), 3), las = 2,
              cex.names = 0.75, ylim = c(0,20), yaxt = "n")

# Now set up the y axis tick marks and labels
ticks <- seq(0, 20, 2)
axis(2, at = ticks, las = 1, 
     labels = formatC(ticks, format = "f", digits = 1))

# Draw a box around the whole thing

# Now draw the years. Note from ?barplot that colMeans(mp) are
# the group midpoints
mtext(side = 1, at = colMeans(mp), line = 3.5, text = colnames(MyData))

# Now draw the x axis label
mtext(side = 1, line = 5.5, text = "Test and Year")

Hope that gets you what you need. You can adjust the font sizes, etc. as
you require.

Note that unlike Excel, the 0 (zero) columns are not dropped. :-)


Marc Schwartz

More information about the R-help mailing list