Question

I have a dataset that look like the following

| SUBJECT | ACTION | DURATION |
|---------|--------|----------|
| 1       | A      | 39,57    |
| 1       | B      | 1,48     |
| 1       | B      | 53,22    |
| 1       | A      | 10,42    |
| 1       | C      | 8,33     |
| 1       | D      | 1,00     |
| 1       | E      | 7,50     |
| 1       | D      | 0,35     |
| 2       | D      | 1,35     |
| 2       | B      | 2,60     |
| 2       | C      | 1,47     |
| 2       | D      | 1,13     |
| 2       | A      | 4,23     |
| 2       | A      | 1,62     |
| 2       | A      | 7,58     |
| 2       | C      | 133,47   |
| 2       | D      | 14,82    |
| 3       | D      | 0,45     |
| 3       | D      | 1,07     |
| 3       | A      | 61,62    |
| 3       | D      | 42,45    |
| 3       | D      | 4,47     |
| 3       | B      | 100,92   |
| 3       | E      | 9,05     |
| 3       | C      | 9,55     |

Which represents 3 subjects performing actions (starting at the same time) for a certain duration. Example, subject 1 performed action A for 39.57 minutes, then action B for 1.48 minutes, then action B again for 53.22 minutes (it is important to differentiate subsequent actions although of the same category).

I would like to plot such data as in the image below enter image description here

Where each horizontal bar represents all the action of a certain subject, the length of component of the bar represents the duration and its colour represents the type of action (A, B, C, etc).

Any help with this? Thanks

Was it helpful?

Solution

Try this:

library(ggplot2)
ggplot(DF, aes(SUBJECT, DURATION, fill = ACTION)) + 
  geom_bar(stat = "identity") +
  coord_flip()

enter image description here

Here is the data frame used (to make it reproducible). Next time please use dput to output the data in the question.

DF <- 
structure(list(SUBJECT = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), ACTION = structure(c(1L, 2L, 2L, 1L, 3L, 4L, 5L, 4L, 4L, 2L, 
3L, 4L, 1L, 1L, 1L, 3L, 4L, 4L, 4L, 1L, 4L, 4L, 2L, 5L, 3L), .Label = c("A", 
"B", "C", "D", "E"), class = "factor"), DURATION = c(39.57, 1.48, 
53.22, 10.42, 8.33, 1, 7.5, 0.35, 1.35, 2.6, 1.47, 1.13, 4.23, 
1.62, 7.58, 133.47, 14.82, 0.45, 1.07, 61.62, 42.45, 4.47, 100.92, 
9.05, 9.55)), .Names = c("SUBJECT", "ACTION", "DURATION"), 
class = "data.frame", row.names = c(NA, 
-25L))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top