简体   繁体   English

如何在一个箱形图中获得两个X轴

[英]How to get two x-axes in one boxplot

I'm trying to get two x-axes in a boxplot in ggplot2; 我试图在ggplot2的箱线图中获得两个x轴; one is Site and the other is Region. 一个是站点,另一个是区域。 I have 11 different Sites and 3 Regions, and want to display my data such that Region is below Site, encompassing a few sites each. 我有11个不同的站点和3个区域,并希望显示我的数据,使“区域”位于“站点”下方,每个站点都包含几个站点。

I've tried facet wrapping and gridding, but I want only one graph where all observations are displayed. 我已经尝试过分面换行和网格化,但是我只想显示所有观察结果的一张图。

My data looks somewhat like this: 我的数据看起来像这样:

Region   Site     Value
South   Site1       0.1
South   Site1       0.3
South   Site2      0.24
South   Site2      0.03
South   Site3      0.06
South   Site3      0.14
South   Site3      0.02
Central Site4       0.4
Central Site4      0.32
Central Site4      0.45
Central Site5      0.22
Central Site5      0.27
Central Site5      0.13
Central Site6      0.09
North   Site7      0.55
North   Site7      0.34
North   Site8      0.67
North   Site9      0.89 
North   Site9       0.7
North   Site9      0.51

The relevant code looks somewhat like this: 相关代码如下所示:

graph <- ggplot(dataframe, aes(x=Site, y=Value)) + geom_boxplot()

I'm hoping to get one graph where the Sites are represented by their associated Regions, ideally with each region label only showing up once under the set of the Sites each represents. 我希望得到一个图,其中站点由其关联的区域表示,理想情况下,每个区域标签在每个站点所代表的位置下仅显示一次。

Use ordered factors to groups levels in variables. 使用有序因子将变量级别分组。 I used y-axes because the Region levels are cardinal. 我使用y轴是因为“ Region级别是基数。

Best, Tyler 最好的,泰勒

library(tidyverse)

dat <- tribble(
  ~Region,   ~Site,   ~Value,
  "South",   "Site1",    0.1,
  "South",   "Site1",    0.3,
  "South",   "Site2",   0.24,
  "South",   "Site2",   0.03,
  "South",   "Site3",   0.06,
  "South",   "Site3",   0.14,
  "South",   "Site3",   0.02,
  "Central", "Site4",    0.4,
  "Central", "Site4",   0.32,
  "Central", "Site4",   0.45,
  "Central", "Site5",   0.22,
  "Central", "Site5",   0.27,
  "Central", "Site5",   0.13,
  "Central", "Site6",   0.09,
  "North",   "Site7",   0.55,
  "North",   "Site7",   0.34,
  "North",   "Site8",   0.67,
  "North",   "Site9",   0.89, 
  "North",   "Site9",    0.7,
  "North",   "Site9",   0.51)

dat <- 
  dat %>% 
  mutate(
    Region = factor(x = Region, levels = c("South", "Central", "North"), ordered = T), 
    Site = factor(x = Site) %>% fct_rev())

ggplot(data = dat, mapping = aes(x = Region, y = Value, position = fct_rev(Site), fill = Site)) + 
  geom_boxplot() + 
  coord_flip()

图.png

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

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