Stacked bar chart across multiple columns

◇◆丶佛笑我妖孽 提交于 2021-02-05 08:12:15

问题


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.


回答1:


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")

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)


来源:https://stackoverflow.com/questions/47801705/stacked-bar-chart-across-multiple-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!