Hey Simon,
You haven't said what you'd like to use to generate the plot, so I'll answer assuming you're agnostic on this and use ggplot2
(which is great for making such plots).
The way I would start is by rearranging your data a bit. That is, put it in a "long" format, rather than a "wide" format.
Here is an example of what I mean:
# Long Format:
"Name" "Weight " "Date"
Bob 72.1 2021-07-12
Bob 72.0 2021-07-13
Bob 72.1 2021-07-13
# Wide Format:
"Name" "2021-07-12" "2021-07-13" "2021-07-14"
Bob 72.1 72.0 72.1
tidyr
has functions for wrangling data between these formats (pivot_wider
/pivot_longer
).
I've recreated your df in this long format here:
df <- data.frame(sample = c("S1","S2","S3","S1","S2","S3"),
part = c("part1","part2","part1","part2","part1","part2"),
value = c(0.898,0.406,0.394,0.102,0.594,0.606))
Once you have this, here is what you tell ggplot
:
ggplot(df, aes(x = sample,
y = value,
fill = part)) +
geom_bar(position= "stack",
stat = "identity")
Defining aes
(aesthetics of the plot), you are telling ggplot
that you want the sample on the x axis, the value on the y axis, but you want the fill
(i.e. color with which the bar is filled) to be determined by part. In the next part (geom_bar
) you're telling ggplot
you want a bar plot (by calling geom_bar
itself), then that you want the bars stacked. In stat="identity"
you're telling ggplot
to use the values you're providing for the y-axis. (By default, geom_bar
likes to count what you're asking it to plot, so if you're providing values, you have to override this default.)
I hope this helps,
Luke