1

I am trying to create a stacked area graph. I'm completely new at R so simple functions like these are still a bit hard... I used the following code:

# stacked area chart
ggplot(specimens_all_together, aes(x=`samplesite`, y =`value`, fill=`variable`)) + 
  geom_area(mapping = NULL,
            data = specimens_all_together,
            stat = "identity",
            position = "stack",
            na.rm = FALSE,
            orientation = NA,
            show.legend = NA,
            inherit.aes = TRUE,
            outline.type = "upper")

The table I am referring to (specimens_all_together_) has been loaded in from excell and kinda looks like (i simplified the names a bit):

sample site  | variable | value  
I            | worm     | 5 
I            | bird     | 6
I            |fish      | 3
II           | worm     | 0
II           | bird     | 0
III          | fish     | 1
IV           | worm     | 5
IV           | bird     | 3
IV           | fish     | 0
....         | ...      |...

but when i do all this, i get a graph with on the Y-axis indeed the values, a really nice legend with all worm, bird and fish types, on the x-axis I also see the sample site values, but the stacked graph, aka the 'fill' is missing. So its just an empty graph. What am I doing wrong???

PS: when i use the geom_bar(position='stack', stat='identity'), i do get a stacked bar plot so I am a bit confused.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
maritos
  • 11
  • 4
  • okay i tried to format it as a table, but i hope you get what i mean by table. Three headers: 'sample site, 'variable' and 'value'. and then below you can kinda see that sample site varies from (I-IV), variable consists of either (bird, fish or worm) and the values vary from (0-6) – maritos Oct 26 '22 at 18:52
  • It seems like you've copied all the defaults from from `geom_area()` and specified them. And you don't need backticks unless you have non-standard column names (e.g., with spaces or punctuation in them). Simplify down to `ggplot(specimens_all_together, aes(x = samplesite, y =value, fill = variable)) + geom_area()` and see if it works. – Gregor Thomas Oct 26 '22 at 18:53
  • (And make sure your column names match. In your table the first column is `sample site`. In your plot code you use `\`samplesite\`` with no space. If there's a space in the column name, use backticks and include the space in the plot code.) – Gregor Thomas Oct 26 '22 at 18:55
  • With a categorical x-axis, you'll also need to add a `group` aesthetic to tell ggplot how to connect things. Inside `aes()`, add `group = variable`. – Gregor Thomas Oct 26 '22 at 18:58
  • haha yess i added the defaults becasue geom_area() alone was not working. I will try removing the backticks and add the group = variable! – maritos Oct 26 '22 at 19:01
  • adding the group = variable did the trick, thanks a lot!!!!!!!!! – maritos Oct 26 '22 at 19:05

0 Answers0