Skip to content

horiz barplot with 2 values for each year

3 messages · yakov peretz, Marc Schwartz

#
Hi,

I'm trying to plot a graph where for each year I have 2 numbers best and
worse. for example for year 2003 I will two values 3.2 and 5.4, and for
year 2004 I will have 3.5 and 6, and so on.



 2003  XXXX
        XXXXXX

2004   XXXXX
        XXXXXXXX

For the same year the 2 entries, if possible, will have different color,
and will be on the graph without space between them. The space will be
between  the years only.

Thnx Yakov
#
yakov peretz wrote:
Yakov,

Try this:

# Create a matrix containing your data
# with one column per year, in this case 2
mydata <- matrix(c(3.2, 5.4, 3.5, 6), ncol = 2)

# Set the column names to be the years
colnames(mydata) <- c(2003, 2004)

# Look at the structure of the data
mydata

# Create the barplot, setting 'beside' = TRUE
# to generate pairs of bars per year
barplot(mydata, beside = TRUE)

By default the color of the first bars will be different than the colors 
of the second bars. You can also explicitly set the colors in the call 
to barplot() using the 'col' argument.

See ?barplot for more information.

Hope that helps,

Marc Schwartz
#
Marc Schwartz wrote:
Yakov,

Quick correction, I forgot to set the barplot to horizontal and I noted 
that you want the years to be decreasing as you go down the y axis.  So, 
  use this sequence instead:

mydata <- matrix(c(5.4, 3.2, 6, 3.5), ncol = 2)
colnames(mydata) <- c(2003, 2004)
mydata

# This call reverses the columns in 'mydata' by year and sets
# 'horiz' = TRUE to do a horizontal bar plot. The 'las = 1'
# sets the y axis labels to horizontal as well.

barplot(mydata[, rev(colnames(mydata))], beside = TRUE,
         horiz = TRUE, las = 1)

Sorry for the oversight.

Marc