如何使用 scale_fill_manual 函数和 ggprism add_pvalue 函数向 ggplot2 中的分组条形图添加图例和 p 值?

问题描述 投票:0回答:0

我遇到了一个问题,我可以用彩色填充和图例创建分组条形图,但是当我尝试使用 ggprism add_pvalue 或 stat_pvalue 手册添加 p 值时,出现错误:

Error:
! Problem while computing aesthetics.
ℹ Error occurred in the 3rd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (1)
✖ Fix the following mappings: `fill`
Run `rlang::last_trace()` to see where the error occurred.

但是,当我删除 aes 中的 fill 参数时,我添加 p 值的代码有效,但我不再有图例了。

有什么办法可以让我在这个图表上同时获得 pvalues 和图例?

创建条形图

library(ggplot2)
library(ggpubr)
treatment = c("A", "A", "B", "B", "C", "C")
means = c(0.7540003, 0.7406441, 0.5396347, 0.4687308, 0.7279047, 0.5106943)
condition = c(1,2,1,2,1,2)
SEM.test = c(0.06276783, 0.06754321, 0.04328225, 0.03137415, 0.04066287, 0.03426278)
Drug = c("A", "B", "A", "B", "A", "B")
color = c("lightgray", "darkgray", "lightgray", "darkgray", "lightgray", "darkgray")
barplot.dataframe = data.frame(treatment, means, condition, SEM.test)
Bargraph = ggplot(barplot.dataframe, aes(treatment, means, group = condition, fill = Drug)) 
Bargraph = Bargraph + geom_col(width = 0.75, position = "dodge", color="black")
Bargraph = Bargraph + geom_errorbar(aes(ymin = means-SEM.test, ymax = means+SEM.test), width = 0.25,                 position = position_dodge(0.75)) 
Bargraph = Bargraph + labs(y = "DR", x = "Task")
Bargraph = Bargraph + scale_fill_manual (values = color)
Bargraph

当我删除 fill 参数时,会创建一个包含 p 值但没有图例的分组条形图


    library(ggprism)
    bargraph.p.val.19 = data.frame(group1 = .8125, group2 = 1.1875, label = 0.887, y.position= .845)
    bargraph.p.val.20 = data.frame(group1 = 1.8125, group2 = 2.1875, label = 0.206, y.position=.64)
    bargraph.p.val.28 = data.frame(group1 = 2.8125, group2 = 3.1875, label = 0.001, y.position=.828)
    Add_P = Bargraph + add_pvalue(bargraph.p.val.20, xmin = "group1", xmax = "group2", label = "label",       y.position = "y.position") 
    Add_P = Add_P + add_pvalue(bargraph.p.val.19, xmin = "group1", xmax = "group2", label = "label",     y.position = "y.position") 
    Add_P = Add_P + add_pvalue(bargraph.p.val.28, xmin = "group1", xmax = "group2", label = "label",     y.position = "y.position")
    Add_P



**Any time I try to add the p values with the fill argument it gives me this**



    Error:
    ! Problem while computing aesthetics.
    ℹ Error occurred in the 3rd layer.
    Caused by error in `check_aesthetics()`:
    ! Aesthetics must be either length 1 or the same as the data (1)
    ✖ Fix the following mappings: `fill`
    Run `rlang::last_trace()` to see where the error occurred.
ggplot2 bar-chart legend p-value
© www.soinside.com 2019 - 2024. All rights reserved.