1

I managed to transform my initial dataset into this form:

   ElemId total_count coef_true coef_false coef_ratio
 1  a1           2         2          0          1
 2  a2           4         4          0          1
 3  a3           1         1          0          1
 4  a4           5         5          0          1
 5  a5           1         1          5          1
 6  a6           4         4          0          1
 7  a7           4         4          3          1
 8  a8           2         2          2          1
 9  a9           3         3          1          1
10  a10           1         1          4          1

Right now what am I trying to achieve is to plot stacked bar chart showing the coef_true and coef_false on single bars using ggplot, while preserving order by coef_ratio. Is there a way to do it without further transforming the dataset?

EDIT. Modifying data is OK, although I tried using melt with melt(valves, measure.vars=c("init_true", "init_false")) and the bar chart seems to loose ordering of coef_ratio.

TheMP
  • 8,257
  • 9
  • 44
  • 73
  • You don't allow any `melt` operations, right? And second thing - You want two bars in each a separate colour for the `ElemId`, correct? – storaged Dec 13 '17 at 20:45
  • Sorry, quite imprecise statement of me. I was afraid that data manipulation will loose the order of the data, I allow melts etc. but I just want to have a chart with coefs for each `ElemId` while preserving the order of bars by `coef_ratio` that goes from 1 to 0 – TheMP Dec 13 '17 at 20:49
  • Can you show enough data or a subset that has both `coef_ratio` 1 and 0, etc.? – M-- Dec 13 '17 at 21:19

1 Answers1

2

If I understand correctly, you want to plot coef values over ElemId where ElemId is reordered by coef_ratio. If this is the case, you could do the following:

library(tidyverse)

df %>% 
  gather(key, value, -c(coef_ratio, ElemId, total_count)) %>% 
  ggplot(aes(reorder(ElemId, coef_ratio), value)) +
  geom_col(aes(fill = key)) +
  labs(x = "ElemId reordered by coef_ratio")

enter image description here

I modified the data so that ElemId a10 has a coef_ratio of 0 to show the reordering of the x axis.

text <- "ElemId total_count coef_true coef_false coef_ratio
       1   a1           2         2          0          1
       2   a2           4         4          0          1
       3   a3           1         1          0          1
       4   a4           5         5          0          1
       5   a5           1         1          5          1
       6   a6           4         4          0          1
       7   a7           4         4          3          1
       8   a8           2         2          2          1
       9   a9           3         3          1          1
       10  a10          1         1          4          0"

df <- read.table(text = text, header = TRUE, stringsAsFactors = FALSE)
tyluRp
  • 4,678
  • 2
  • 17
  • 36