【问题标题】:Unstacking and Grouping Barchart with ggplot2 [duplicate]使用ggplot2取消堆叠和分组条形图[重复]
【发布时间】:2019-01-18 03:20:32
【问题描述】:

我是 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

如您所见,我使用了闪避,但似乎没有用,我想取消堆叠,以便将每种类型的所有重复组合在一起。

非常感谢!

【问题讨论】:

  • 问题在于您的数据格式。查看stackoverflow.com/questions/5963269/…,编辑您的帖子,以便我重新创建您的数据,我会为您提供帮助。
  • @BenG 有帮助吗?
  • 是的,我在下面提供了答案。干得好。

标签: r ggplot2 bar-chart data-visualization


【解决方案1】:
# 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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2017-11-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多