跨多列的堆积条形图 [英] Stacked bar chart across multiple columns
问题描述
我设法将初始数据集转换为以下形式:
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
现在我要实现的是使用ggplot绘制堆积条形图,显示在单个柱上的coef_true和coef_false,同时按coef_ratio保留顺序.有没有办法进一步转换数据集吗?
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?
编辑.修改数据还可以,尽管我尝试通过 melt(valves,measure.vars = c("init_true","init_false"))
和条形图似乎失去了coef_ratio的顺序.
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.
推荐答案
如果我正确理解,您想在 ElemId
上绘制coef值,其中 ElemId
由<代码> coef_ratio .在这种情况下,您可以执行以下操作:
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")
我修改了数据,以便 ElemId
a10
的 coef_ratio
为0,以显示x轴的重新排序.
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)
这篇关于跨多列的堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!