0

I'm working with R for the first time and I came to a problem a can't solve.

I measured the "working time" and the "study time" of students. Together they result in the "workload" of the students. I would like to create a histogram that depicts the workload and differentiates color between working hours and study time.

Just like a stacked barplot, but as histogram, without any categorical variable.

I searched the internet for a long time, but I did only find stacked barplots, overlapping histograms or densityplots.

Your help will be highly appriciated

Edit: My Data looks like

    VP     Work   Study     Workload
     1     10     20        30
     2     30     20        50
     3     20     40        60
     ...   ...    ...

So the bars of the Histogram shoul have a hights of 30, 50 and 60 an be proportional colored for "work" and "study".

Tali
  • 3
  • 2
  • Does this answer your question? [Stacked Bar Plot in R](https://stackoverflow.com/questions/20349929/stacked-bar-plot-in-r) – jay.sf Jan 21 '20 at 16:50
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jan 21 '20 at 17:01

1 Answers1

0

From your edit, I assuming that you want one bar for each student with their total hours. Something like this?

I am using ggplot2 and functions from tidyverse packages.

library(dplyr)
library(tidyr)
library(ggplot2)

df <- tibble(VP = 1:3,
             Work = c(10, 30, 20),
             Study = c(20, 20, 40),
             Workload = c(30, 50, 60)) # Or simply `Workload = Work + Study`

df %>% 
  select(-Workload) %>% 
  tidyr::gather(-VP, key = "type", value = "time") %>% 
  ggplot(aes(x = factor(VP), y = time, fill = type)) +
    geom_col(position = "stack") # `position` argument defines the stacked bars

enter image description here

Gabriel M. Silva
  • 642
  • 4
  • 10
  • Your assumption is right and your code worked out well. Thank you very well for your efford. Do you now, if the bars can also be sorted according to the length of the workload variable? – Tali Jan 21 '20 at 19:31
  • Use the `reorder()` function in your `ggplot(data, aes(x = ...), ...)` call: replace `factor(VP)` by `reorder(factor(VP), time)` or `reorder(factor(VP), desc(time))` (for ascending or descending order, respectively). And always click on the button "Accept answer" if it solves your problem. – Gabriel M. Silva Jan 21 '20 at 19:57
  • Thank you! From now on I think of the button. That was my first question here, I hope I will improve over time. – Tali Jan 22 '20 at 20:22