簡體   English   中英

使用數據框中的所有列在ggplot2中繪制箱線圖

[英]Plotting a boxplot in ggplot2 using all columns in a data frame

我正在嘗試為數據框中的所有列繪制箱形圖。 我可以通過R的本機boxplot函數來實現。

boxplot(sam_som_2, use.cols = TRUE, xlab = "Samples", ylab = "Frequency", outline=FALSE)`

但是我不能用ggplot2達到同樣的ggplot2 這使我一個或另一個錯誤。

以下是我要使用ggplot2繪制的圖。

在此處輸入圖片說明

這是我數據框的一部分。

dput(my_data)
structure(list(`1` = c(875L, 1102L, 1028L, 925L), `2` = c(845L, 
1065L, 1052L, 925L), `3` = c(840L, 1131L, 1080L, 953L), `4` = c(1006L, 
1211L, 1120L, 556L), `5` = c(965L, 1271L, 1061L, 663L), `6` = c(995L, 
1245L, 1125L, 395L), `7` = c(1026L, 1244L, 1109L, 607L), `8` = c(1087L, 
1220L, 1068L, 601L)), .Names = c("1", "2", "3", "4", "5", "6", 
"7", "8"), class = "data.frame", row.names = c(NA, -4L))

可以找到重復項的可能重復項。 從ggplot2 [duplicate]中的x上的列名,用數據框的所有列構建箱形圖 話雖如此,這是您可以做的:

my_data <- read.csv("sam_som_2.csv", header = TRUE, check.names = FALSE)
# check.names= FALSE retains the names as they're in the dataframe
# -------------------------------------------------------------------------
dput(my_data)

structure(list(`1` = c(875L, 1102L, 1028L, 925L), `2` = c(845L, 
1065L, 1052L, 925L), `3` = c(840L, 1131L, 1080L, 953L), `4` = c(1006L, 
1211L, 1120L, 556L), `5` = c(965L, 1271L, 1061L, 663L), `6` = c(995L, 
1245L, 1125L, 395L), `7` = c(1026L, 1244L, 1109L, 607L), `8` = c(1087L, 
1220L, 1068L, 601L)), .Names = c("1", "2", "3", "4", "5", "6", 
"7", "8"), class = "data.frame", row.names = c(NA, -4L))
# -------------------------------------------------------------------------
library(ggplot2)
ggplot(stack(my_data), aes(x = ind, y = values)) +
labs(x="Samples", y="Frequency") +
geom_boxplot(fill = "white", colour = "#3366FF")
# produces the following output.
# -------------------------------------------------------------------------

box_plot_01

如果您需要圍欄,則可以使用errorbar欄來利用它,如下所示:

ggplot(stack(my_data), aes(x = ind, y = values)) +
  stat_boxplot(geom = "errorbar", width = 0.5) +
  labs(x="Samples", y="Frequency") +
  geom_boxplot(fill = "white", colour = "#3366FF") 

輸出如下: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM