[R] using csv file for stacked bar plot, rows to columns

Sarah Goslee sarah.goslee at gmail.com
Thu Oct 13 02:29:32 CEST 2011


Hi,

On Wed, Oct 12, 2011 at 6:11 PM, Davis_fishgirl <lrledesma at gmail.com> wrote:
>
> **NEW TO R**-been trying to teach myself with no prior experience in
> computer languages, so I apologize if I am poor at using technical terms
> Hi, I have perused some of the previous posts on this topic and tried their
> solutions, but am still coming up with error messages(sometimes more than 50
> at a time)
>
> I have:
> a csv file with four columns(that I have read into R, no problem, we will
> call it DATA)
> date, Location1, Location2, total
>
> Dates cover almost a year
> location values are number of fish seen at that location

So your question doesn't have anything to do with CSV files, but
only with making a stacked barplot from a data frame.

> I would like to show a stacked bar plot so someone can see the breakdown for
> total fish seen on any particular day.  I was able to create a simple bar
> plot for total number of fish versus Date, but when I have tried to make a
> stacked graph it creates four bars(one for each column).
>
> Do I have to convert my data so each date has its own column or is there a
> way I can use my data as is?
>
> script I have tried:
>
> barplot(as.matrix(DATA))
>
> barplot(t(DATA),names.arg=DATA$Date)
>
> fish<-table(DATA$Location1,DATA$Location2)
> barplot(fish,names.arg=DATA$Date)

If you read the help for barplot, you'll see that the argument beside
controls whether the bars are next to each other or stacked.

You'll get better answers if you provide a reproducible example (see
posting guide, please), but this may be enough to get you going.

> testdata <- data.frame(Date=1:5, Location1=sample(1:10, 5, replace=TRUE), Location2=sample(1:10, 5, replace=TRUE))
>
> testdata
  Date Location1 Location2
1    1         3        10
2    2        10         6
3    3         2         9
4    4         4        10
5    5         8         2
> barplot(t(testdata[, 2:3]), beside=FALSE, names=testdata$Date)

Sarah

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list