【问题标题】:Graphing four plots together with a common legend用一个共同的图例绘制四个图
【发布时间】:2019-07-19 18:00:39
【问题描述】:

我编写了代码来制作四种栖息地类型中物种数量的条形图。我总共有 8 个物种,但并非所有物种都存在于每个栖息地。我想要四个栖息地类型的多面板图表,并带有该物种的共同图例。目前,每个条形图都有自己的图例,不同的颜色对应不同的物种。

[Graph of RV][1]
[Graph of CG][2]
[Graph of U][3]
[Graph of SRG][4]

下面是使用的代码

ggplot(SRG, aes(x = Species)) +
geom_bar(aes(color = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

ggplot(U, aes(x = Species)) +
geom_bar(aes(color = Species, , fill = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

ggplot(CG, aes(x = Species)) +
geom_bar(aes(color = Species, fill = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

ggplot(RV, aes(x = Species)) +
geom_bar(aes(color = Species, fill = Species),
stat = "count", position = position_dodge(0.8),
width = 0.9)+
labs(y= "Count", x= "Species")

【问题讨论】:

标签: r ggplot2


【解决方案1】:

你可以试试 par(mfrow = c(2,2)

#Code 
 par(mfrow = c(2,2)
 #Code of Graph 1
 #Code of Graph 2
 #Code of Graph 3
 #Code of Graph 4

【讨论】:

    【解决方案2】:

    由于您的所有数据都采用相同的格式,您可以将数据帧与 rbind 结合起来。

    combined_df <- rbind(SRG, CG, U, RV)
    
    ggplot(combined_df, aes(x = Species)) +
    geom_bar(aes(color = Species),
    stat = "count", position = position_dodge(0.8),
    width = 0.9)+
    labs(y= "Count", x= "Species")
    

    【讨论】:

    • 这给出了所有栖息地的总数。我想在图表上绘制所有四个栖息地。
    • 在这种情况下,您可以向每个数据框 rv 添加一列
    • 这行得通,但它太大了。这个想法是有一个多面图,所有四个栖息地都单独显示,并带有一个共同的图例。问题已被编辑。
    • 好的,然后像上面一样将栖息地绑定到每个数据帧,然后重新绑定数据帧。在 ggplot aes 中设置 color = species,并将 +facet_wrap('habitat') 添加到 ggplot 参数的末尾。
    猜你喜欢
    • 2016-10-18
    • 2020-07-27
    • 1970-01-01
    • 2018-09-24
    • 2019-12-23
    • 2019-05-27
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多