【问题标题】:How to make three different bar charts of similar type clustered in the same plot?如何使三个相似类型的不同条形图聚集在同一个图中?
【发布时间】:2019-09-19 18:29:27
【问题描述】:

我需要用三个土壤深度(行(A1、A2、A3))绘制不同耕作水平(列)的侵蚀值。我希望所有这些都显示为单个图中的条形图。

这是一个可重现的例子:

a<- matrix(c(1:36), byrow = T,  ncol = 4)
rownames(a)<-(c("A1","B1","C1","A2","B2","C2","A3","B3","C3"))
colnames(a)<-(c("Int_till", "Redu_till", "mulch_till", "no_till"))

barplot(a[1,], xlab = "A1", ylab = "Erosion") 
barplot(a[4,], xlab = "A2", ylab = "Erosion")
barplot(a[7,], xlab = "A3", ylab = "Erosion")
##I want these three barchart side by side in a single plot
## for comparison 

### and need similar plots for all the "Bs" and "Cs"  
### Lastly, i want these three plots in the same page.

我看到人们在 ggplot(用于线条)中使用“填充”来做类似的事情,并指定可以很好地将图表区分为不同类别的因素,但我尝试这样做但总是遇到错误,可能是因为我的数据是连续的。

如果有任何机构可以在这两件事上帮助我.. 这将是一个很大的帮助。我会很感激的。

谢谢!

【问题讨论】:

  • 如果你在ggplot做这个,可以用facet_wrap或者base R,改par
  • 你可以做par(mfrow = c(3, 1))然后运行barplot语句
  • 你需要library(reshape2); library(ggplot2);&gt; melt(a) %&gt;% ggplot(., aes(x = Var2, y = value, fill = Var1)) + geom_bar(stat = 'identity', position = position_dodge2(preserve = "single"))

标签: r ggplot2 bar-chart


【解决方案1】:

我们可以使用ggplot

library(reshape2)
library(ggplot2)
library(dplyr)
melt(a) %>%
      ggplot(., aes(x = Var2, y = value, fill = Var1)) + 
         geom_bar(stat = 'identity',
              position = position_dodge2(preserve = "single")) + 
         facet_wrap(~ Var1)

【讨论】:

  • 非常感谢。我也喜欢这个。我在上面也问过这个问题,我如何在这个图中将每一行标记为“A”、“B”或“C”?所以在图表的左侧,每一行都有像“A”、“B”和“C”这样的标签。我还尝试使用 (+ labs(title = "title")) 添加标题,但标题只出现在侧面。我该如何解决这个问题?
【解决方案2】:

设置mfcol 以指定一个 3x3 网格,然后为每一行生成其条形图。此外,您可以考虑添加 barplot 参数 ylim = c(0, max(a)) 以便所有图形使用相同的 Y 轴。 titlemtext 可用于设置整体标题和各种边距文本,如下所示。请参阅?par?title?mtext 了解更多信息。

opar <- par(mfcol = c(3, 3), oma = c(0, 3, 0, 0))
for(r in rownames(a)) barplot(a[r, ], xlab = r, ylab = "Erosion")
par(opar)

title("My Plots", outer = TRUE, line = -1)
mtext(LETTERS[1:3], side = 2, outer = TRUE, line = -1, 
  at = c(0.85, 0.5, 0.17), las = 2)

【讨论】:

  • 谢谢你,这非常好。我能够做到第一行的所有 A,第二行的所有 B 和第三行的所有 C。您能否告诉我如何在此图中将每一行标记为“A”、“B”或“C”?因此,在图表的左侧,每行都有“A”、“B”和“C”之类的标签。另外,如何为整个情节添加标题?
  • 非常感谢您的帮助。我很感激。
猜你喜欢
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2021-05-31
  • 2012-06-29
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 2019-07-04
相关资源
最近更新 更多