我仍然是 R 的新手,我有一些關于使用 ggplot 的問題和幫助。
我一直在使用 spadeR 來獲取每個采樣位置的物種豐富度和多樣性,我想為我的資料可視化制作條形圖。但是我在獲取 ggplot 的正確代碼時遇到了一些麻煩。
這是我想要的資料可視化的示例。

但我的條形圖看起來像這樣

我想在框架頂部添加一個圖例,我嘗試添加它,但結果非常糟糕。
誰能告訴我如何使用 ggplot 解決此問題,以及如何像上面的示例一樣在一個框架中制作 2 個條形圖,如何使用 parfrow?希望有人能教我如何解決這個問題。非常感謝!
在這里,我的 10 個采樣位置的物種豐富度資料集包括物種豐富度和標準誤差的估計分數。
datalw <- as.matrix(data.frame(Bng = c(8, 0.4),
Krs= c(3, 0),
Bny= c(3, 0),
Kmb= c(9.1, 7.40),
Sgk= c(3, 0.3),
Lwb= c(6.4, 1.0),
Lws= c(4.3, 0.7),
Krm= c(3, 0.5),
Hrt= c(7, 0.5),
Gmb= c(6.5, 1.0)))
rownames(datalw) <- c("Estimates", "s.e")
datalw
barplot(datalw,
col = c("#1b98e0", "#353436"))
legend("top",
legend = c("estimates", "s.e"),
fill = c("#1b98e0", "#353436"))
uj5u.com熱心網友回復:
我不得不玩弄你的資料。您不必制作datalw矩陣,因為它最終會導致問題。您的資料也有多列而不是多行,所以我為您重新格式化了您的資料。
datalw <- structure(list(loc = structure(c(1L, 7L, 2L, 5L, 10L, 8L, 9L,
6L, 4L, 3L), .Label = c("Bng", "Bny", "Gmb", "Hrt", "Kmb", "Krm",
"Krs", "Lwb", "Lws", "Sgk"), class = "factor"), V1 = c(8, 3,
3, 9.1, 3, 6.4, 4.3, 3, 7, 6.5), V2 = c(0.4, 0, 0, 7.4, 0.3,
1, 0.7, 0.5, 0.5, 1)), class = "data.frame", row.names = c(NA,
-10L))
由于您希望將條形并排放置,您可以將這些資料融合在一起以更輕松地繪制資料
library(ggplot2)
library(ggpattern)
library(reshape2)
datalw2 <- melt(datalw, id.vars='loc')
有一種制作圖案的方法ggplot可以使用ggpattern
ggplot(datalw2,aes(x=loc, y=value, fill=variable, group=variable, pattern = variable))
geom_bar_pattern(stat='identity', position='dodge')
scale_pattern_manual(values = c(V1 = "stripe", V2 = "crosshatch"))
這將產生這樣的情節。有更高級的方法可以像在圖片中一樣更改圖案,但是,您必須自己創建圖案,而不是使用來自的默認圖案ggpattern

您的資料沒有足夠的資訊來創建圖片中顯示的誤差條
你也可以像這樣使情節黑白分明
ggplot(datalw2,aes(x=loc, y=value, fill=variable, group=variable, pattern = variable))
geom_bar_pattern(stat='identity', position='dodge')
theme_bw()
scale_pattern_manual(values = c(V1 = "stripe", V2 = "crosshatch"))
scale_fill_grey(start = .9, end = 0)

有一種方法可以像您的圖片一樣創建并排圖,但是您也沒有足夠的資料來制作第二個圖
如果要將誤差線添加到圖形中。您可以使用geom_errorbar. 使用您在下方評論中提供的資料
datadv <- structure(list(caves = structure(c(1L, 7L, 2L, 5L, 10L, 8L, 9L, 6L, 4L, 3L), .Label = c("Bng", "Bny", "Gmb", "Hrt", "Kmb", "Krm", "Krs", "Lwb", "Lws", "Sgk"), class = "factor"), Index = c(1.748, 0.022, 1.066, 1.213, 0.894, 0.863, 1.411, 0.179, 1.611, 1.045), Std = c(0.078, 0.05, 0.053, 0.062, 0.120, 0.109, 0.143, 0.072, 0.152, 0.171)), class = "data.frame", row.names = c(NA,-10L))
library(ggpattern)
library(ggplot2)
ggplot(datadv,aes(x=caves, y=Index))
geom_bar_pattern(stat='identity', position='dodge')
theme_bw()
scale_pattern_manual(values = c(V1 = "stripe", V2 = "crosshatch"))
scale_fill_grey(start = .9, end = 0)
geom_errorbar(aes(ymin=Index-Std, ymax=Index Std), width=.2,
position=position_dodge(.9))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371942.html
上一篇:更改ggplot2中的圖例
