简体   繁体   English

如何使用ggplot2在R中绘制箱形图的比较

[英]How to plot a comparison of boxplots in R using ggplot2

I have a data frame with three variables (n, Parametric, Mean) in column format. 我有一个带有三个列格式的变量(n,参数,均值)的数据框。 n takes on values 25, 50, or 100. Parametric takes on either "Yes" or "No". n取值为25、50或100。参数取“是”或“否”。 Mean takes on a numerical value. 平均值取一个数值。 Similar to the very simplified version here: 类似于此处的非常简化的版本:

n     Parametric     Mean
25       Yes          1.2
25       No           1.5
50       Yes          0.9
50       No           1.1
100      Yes          1.0
100      No           1.2

I would like to make a boxplot comparing the Parametric mean values (mean values that have parametric=yes) vs. Non parametric mean values (mean values that have parametric=no) for each of the three different n values. 我想制作一个箱形图,比较三个不同的n值中的每一个的参数平均值(具有参数=是的均值)与非参数平均值(具有参数=否的均值)。

Similar to the image below: https://www.sthda.com/sthda/RDoc/figure/ggplot2/ggplot2-box-plot-box-plot-multiple-groups-data-visualization-1.png 类似于下图: https : //www.sthda.com/sthda/RDoc/figure/ggplot2/ggplot2-box-plot-box-plot-multiple-groups-data-visualization-1.png

Except I want my legend to be Parametric: Yes or No, the x-values to be n, and the y values to be the mean values. 除了我希望图例为参数:是或否,x值为n,y值为平均值。

The code: 编码:

    # Create boxplot comparisons
    ggplot(dataMean, aes(x=n, y=Mean, color=Parametric))+
        geom_boxplot()

is only giving me something that has two boxplots, one for Parametric=yes and one for Parametric=no. 只是给我一些东西,有两个箱型图,一个用于参数=是,另一个用于参数=否。 I am looking for a plot that compares parametric=yes vs parametric=no for each n value. 我正在寻找一个图表,比较每个n值的parametric = yes和parametric = no。 So ultimately I want 6 boxplots (2 boxplots for each n value), color coordinated by their parametric column. 因此,最终我需要6个箱形图(每个n值2个箱形图),颜色由其参数列协调。

How should I organize my data in order to be able to achieve this result? 我应该如何组织我的数据才能获得此结果? And what code would then create a plot with these 6 boxplots? 然后用什么代码用这6个箱形图创建一个图?

Maybe facet_wrap() can help you. 也许facet_wrap()可以为您提供帮助。 I can demonstrate this with ToothGrowth dataset: 我可以用ToothGrowth数据集来证明这ToothGrowth

data("ToothGrowth")
ggplot(ToothGrowth, aes(x = supp, y = len, fill = supp)) + 
  geom_boxplot(position = position_dodge()) +
  facet_wrap(~dose)

and the plot is like: 和情节是这样的:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM