我是R的新手,我正试图拆解我制作的堆叠条形图。我已经尝试过“ position =“ dodge”函数,但这似乎没有用。
有人知道如何解决吗?
df <- structure(list(Type = c("a", "b", "c", "d", "e", "f", "g", "h","i"),
Repeat_1 = c(10, 39, 1, 8, 2, 25, 11, 14, 4), Repeat_2 = c(11,24, 15, 1, 2,
3, 2, 3, 5), Repeat_3 = c(4, 1, 2, 1, 1, 2, 10,5, 4)), row.names = c(NA, -9L),
class = c("tbl_df", "tbl", "data.frame"))
原始数据:
Type Repeat_1 Repeat_2 Repeat_3
1 a 10 11 4
2 b 39 24 1
3 c 1 15 2
4 d 8 1 1
5 e 2 2 1
6 f 25 3 2
7 g 11 2 10
8 h 14 3 5
9 i 4 5 4
这是我用来可视化的内容:
p<-ggplot(data=df, aes(x=Type, y=Conc.)) +
geom_bar(aes(y=Repeat_1),stat="identity",position ="dodge",alpha=.5,fill='blue',color='blue') +
geom_bar(aes(y=Repeat_2),stat="identity",position ="dodge",alpha=.8,fill='pink',color='red4') +
geom_bar(aes(y=Repeat_3),stat="identity",position ="dodge",alpha=.8,fill='lightgreen',color='green4')
哪个产生:1:https://i.stack.imgur.com/j5t33.png
如您所见,我已经使用了躲避功能,但似乎没有用,我想将其堆叠,以便将每种类型的所有重复分组到一起。
非常感谢!
答案 0 :(得分:0)
# at first it is preferable for ggplot if your data is in long format
library(tidyr)
df_long <- df %>% gather(key = repeat_group, value = val, -1)
# now you can plot the bars next to each other with just one geom_bar
ggplot(data = df_long, aes(x = Type, y = val)) +
geom_bar(aes(fill = repeat_group), stat = "identity",position = "dodge")