我有一个像这样的数据集。
> ds
domanda esito cella
22870 22870 B 3
22893 22893 R 4
16258 16258 P 2
14684 14684 P 2
12873 12873 B 1
12933 12933 B 2
12047 12047 R 2
22880 22880 B 3
11479 11479 P 3
20836 20836 B 3
我需要生成一个在x轴上具有“ cella”元素的图(从1到49,我只向您展示了其中的一部分)。对于每个单元,我想要一个由三种颜色组成的条形,具体取决于相应的P,B,R元素。例如,在cella 2上,我想要一个长度为4的条,颜色为紫色(2个单位),蓝色(1个单位)和红色(1个单位)。我知道可以先使用函数melt
,然后再使用ggplot
(与),但我没有得到想要的东西。有人可以帮忙吗?
我尝试过的是:
> this.col
[1] 2 1 3 3 2 2 1 2 3 2
从该颜色文件(通过“ esito”列获取)开始,我已经执行了以下操作:
ds_som.m = melt(ds_som[,2:3],id=c("cella"))
ggplot(data=ds_som.m, aes(x=ds_som.m$cella, y=ds_som.m$value,
fill=ds_som.m$variable,col=this.col))+
geom_bar(stat = "identity")+
scale_fill_brewer(direction=-1)+
guides(fill = guide_legend(title = "Esiti", title.position = "top"))
我们能试试
library(dplyr)
library(ggplot2)
ds[-1] %>%
group_by(cella) %>%
mutate(n =n()) %>%
unique() %>%
ggplot(., aes(x= cella, y=n, fill=esito)) +
geom_bar(stat='identity', position='dodge')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句