简体   繁体   English

scale_x_discrete 轴标签不正确

[英]Incorrect axis labels with scale_x_discrete

I am trying to plot a ggplot boxplot using facet_wrap to show two sites.我正在尝试使用facet_wrap绘制 ggplot facet_wrap以显示两个站点。 My x axis has three possible treatments, control, bagged, or scattered.我的 x 轴有三种可能的处理方式,控制、袋装或分散。 In order to remove an empty column in the facet_wrap , I have used facet_wrap(~site, scales = "free_x") , as each site contains a control and either bagged or scattered.为了删除facet_wrap中的空列,我使用了facet_wrap(~site, scales = "free_x") ,因为每个站点都包含一个控件,并且要么是装袋的,要么是分散的。 I also want to change my axis labels from 'A_Control' to 'Control' etc, so have used scale_x_discrete(labels = c('Control','Bagged','Scattered')) .我还想将我的轴标签从 'A_Control' 更改为 'Control' 等,因此使用了scale_x_discrete(labels = c('Control','Bagged','Scattered')) However, my problem is when I use the below code to plot it, it removes the label for scattered and replaces it with bagged for site B, and I'm struggling to work out where the problem is.但是,我的问题是当我使用下面的代码来绘制它时,它删除了scattered 的标签并将其替换为bagging for site B,我正在努力找出问题所在。 I have included the incorrect plot at the bottom.我在底部包含了不正确的情节。

  geom_boxplot()+
  stat_summary(fun.y = mean, geom="point", color="red")+
  scale_x_discrete(labels = c('Control','Bagged','Scattered'))+
  facet_wrap(~site, scales = "free_x")


My data:我的数据:

  salmon_biomass = c(0.263678451,0.721658206,
                     0.214856902,0.267343486,0.250631313,0.105008418,2.645833333,
                     1.702020202),
            site = as.factor(c("Site A",
                               "Site A","Site A","Site A","Site B","Site B",
                               "Site B","Site B")),
         section = as.factor(c("A", "A", "B", "B", "A", "A", "B", "B")),
       treatment = as.factor(c("A_Control",
                               "B_Bagged","A_Control","B_Bagged","A_Control",
                               "C_Scattered","A_Control","C_Scattered"))```



阴谋

You can pass a named vector for the labels in scale_x_discrete :您可以为scale_x_discretelabels传递命名向量:

  ggplot(df, aes(treatment, salmon_biomass)) +
    geom_boxplot()+
    stat_summary(fun.y = mean, geom="point", color="red")+
    scale_x_discrete(labels = c(B_Bagged = "Bagged", 
                                A_Control = 'Control',
                                C_Scattered = 'Scattered')) +
    facet_wrap(~site, scales = "free_x")

在此处输入图片说明

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

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