[英]How to make a boxplot on ggplot with two columns for my x-axis and two columns for my y-axis?
I am trying to make a grouped boxplot on ggplot, however, I am running into a problem since I have two columns for my x-axis and two columns for my y-axis and it won't let me plot it.我正在尝试在 ggplot 上制作分组箱线图,但是,我遇到了一个问题,因为我的 x 轴有两列,y 轴有两列,它不会让我 plot 它。
I know that if I have 1 x-axis and two y-axis I can use the gather function
such as:我知道如果我有 1 个 x 轴和两个 y 轴,我可以使用
gather function
例如:
`BB <- BB %>%
gather(key = "Type", value = "KO.Values", MetaT,
MetaG) %>%
convert_as_factor(Type)
ggplot(BB, aes(x=Ocean.region, y=KO.Values, fill=Type)) +
geom_boxplot()+
scale_fill_brewer(palette="Set1")+
scale_y_log10()`
However, this isn't working since I have two x-axis as well.但是,这不起作用,因为我也有两个 x 轴。 Also the Ocean.regionG and MetaG column are shorter than the Ocean.regionT and Meta T columns.
Ocean.regionG 和 MetaG 列也比 Ocean.regionT 和 Meta T 列短。
Any help would be greatly appreciated thank you!任何帮助将不胜感激,谢谢!
Here are the first 10 rows of my dataset.这是我的数据集的前 10 行。
` Ocean.regionT Ocean.regionG MetaT MetaG
AO AO 0.000000000 0.000530614
AO AO 0.006962999 0.002265703
AO AO 0.123946517 0.001184657
Madagascar MS 0.081058488 0.024913063
Madagascar MS 0.049421702 0.008098015
MS MS 0.072319800 0.016901097
MS MS 0.035732418 0.075799616
MS NAO 0.029748322 0.037194669
MS NAO 0.021146596 0.041375374
NAO NAO 0.567529831 0.035902832
NAO NAO 0.602152447 0.013699213
NAO NAO 0.811603574 0.052514921`
It may be better to reshape with pivot_longer
as it is more generalized and can reshape based on the pattern in column name.使用
pivot_longer
进行整形可能会更好,因为它更通用,并且可以根据列名中的模式进行整形。 Here, we specify the names_sep
with a regex lookaround to match between the last upper case letter and the lower case letter in column names, then use ggplot
with 'x' as 'Ocean.region' and the fill
as 'grp' column which include the suffix 'T', 'G'在这里,我们使用正则表达式环视指定
names_sep
以匹配列名中的最后一个大写字母和小写字母,然后使用ggplot
将 'x' 作为 'Ocean.region' 并将fill
作为 'grp' 列,其中包括后缀“T”、“G”
library(dplyr)
library(tidyr)
library(ggplot2)
BB %>%
pivot_longer(cols = everything(), names_to = c(".value", "grp"),
names_sep="(?<=[a-z])(?=[TG]$)") %>%
ggplot(aes(x = Ocean.region, y = Meta, fill = grp)) +
geom_boxplot() +
scale_fill_brewer(palette="Set1") +
scale_y_log10()
-output -输出
BB <- structure(list(Ocean.regionT = c("AO", "AO", "AO", "Madagascar",
"Madagascar", "MS", "MS", "MS", "MS", "NAO", "NAO", "NAO"),
Ocean.regionG = c("AO",
"AO", "AO", "MS", "MS", "MS", "MS", "NAO", "NAO", "NAO", "NAO",
"NAO"), MetaT = c(0, 0.006962999, 0.123946517, 0.081058488, 0.049421702,
0.0723198, 0.035732418, 0.029748322, 0.021146596, 0.567529831,
0.602152447, 0.811603574), MetaG = c(0.000530614, 0.002265703,
0.001184657, 0.024913063, 0.008098015, 0.016901097, 0.075799616,
0.037194669, 0.041375374, 0.035902832, 0.013699213, 0.052514921
)), class = "data.frame", row.names = c(NA, -12L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.