0

I have the following example dataframe:

`Trait Class Value

Trait Class Value
1     A     3
1     B     4
2     A     7
2     B     8

I want to create a barplot with ggplot2 where the values for each class are mirrored on the x axis.

When I try to plot it like this,

ggplot(cali_gca, aes(x=Trait, y=Value, fill=Class)) + 
 geom_bar(stat="identity", position="identity")

I don't get any mirroring on the x axis (see Image with my actual data which is completely the same structured as the toy dataset).

Does anybody has an idea why?

Thank you so much in advance!

Graphic I get

Here is the plot drawn in paint I would like to have: Graphic I want

Olympia
  • 457
  • 8
  • 19
  • 1
    Please draw your expected plot in Paint or any other software and add it to your question – Tung Sep 20 '18 at 14:57
  • You might be looking for something like [this](https://stackoverflow.com/questions/4559229/drawing-pyramid-plot-using-r-and-ggplot2) or [this](https://stackoverflow.com/questions/14680075/simpler-population-pyramid-in-ggplot2)? – Z.Lin Sep 21 '18 at 01:47

1 Answers1

2

You could take the part of the data you want to mirror, multiply it by (-1) and attach it to the dataframe:

library(tidyverse)

df <- tribble(
  ~year, ~country, ~value,
  2001, "France", 55, 
  2002, "France", 53, 
  2003, "France", 31, 
  2004, "France", 10, 
  2005, "France", 30, 
  2006, "France", 37, 
  2007, "France", 54, 
  2008, "France", 58, 
  2009, "France", 50, 
  2010, "France", 40, 
  2011, "France", 49, 
  2001, "USA", 55,
  2002, "USA", 53,
  2003, "USA", 64,
  2004, "USA", 40,
  2005, "USA", 30,
  2006, "USA", 39,
  2007, "USA", 55,
  2008, "USA", 53,
  2009, "USA", 71,
  2010, "USA", 44,
  2011, "USA", 40
)

ggplot(df, aes(year, value, fill = country)) +
  geom_col()

df <- df %>% 
  bind_rows(df %>% 
              filter(country == "France") %>% 
              mutate(value = -value,
                     country = "-France"))

ggplot(df, aes(year, value, fill = country)) +
  geom_col()

Which produces:

enter image description here

ulima2_
  • 1,276
  • 1
  • 13
  • 23