如何添加公共行和文本作为第二个X轴标签

时间:2019-01-08 10:46:35

标签: r ggplot2

我想画一个图。我的多个x轴标签有一个公共标签。因此,我想添加通用文本作为标签,而不是如附图所示在x轴上添加几个单独的标签。该怎么办?

library(dplyr)
library(forcats)
library(ggplot2)

df <- data.frame(conc = c(0, 10, 50, 100, "Positive Control"),
                 values = c(3, 3, 4, 5, 10),
                 name = c("TiO2 NP", "TiO2 NP", "TiO2 NP", "TiO2 NP", "Cyclophosamide"))

df$conc <- as.factor(df$conc)
labels2 <- paste0(df$conc, "\n", df$name)

df %>% 
  mutate(conc = fct_reorder(conc, values)) %>% 
  ggplot(aes(x = conc, y=values, fill = conc))+
  geom_bar(stat = "identity",show.legend = FALSE, width = 0.6)+
  scale_x_discrete(labels = labels2)+
  labs(x = "\n Dose (mg/kg BW)")

2 个答案:

答案 0 :(得分:1)

我认为没有简单的方法。您必须与post一起玩一段时间才能使某些东西真正自定义。这是我的示例:

ggplot2

example plot

答案 1 :(得分:1)

对于更自动化的方法,您可以尝试将公共变量与facet_grid一起放在scales = "free", space = "free"中,以模拟第二条x轴线。下面的代码其余部分是针对美学方面的调整:

df %>%
  mutate(conc = fct_reorder(conc, values)) %>%
  ggplot(aes(x = conc, y = values, fill = conc)) +
  geom_col(show.legend = F, width = 0.6) + #geom_col() is equivalent to geom_bar(stat = "identity")
  facet_grid(~ fct_rev(name), 
             scales = "free", space = "free", 
             switch = "x") + #brings the facet label positions from top (default) to bottom
  scale_x_discrete(expand = c(0, 0.5)) + #adjusts the horizontal space at the ends of each facet
  labs(x = "\n Dose (mg/kg BW)") +
  theme(axis.line.x = element_line(arrow = arrow(ends = "both")), #show line (with arrow ends) to
                                                                  #indicate facet label's extent
        panel.spacing = unit(0, "cm"), #adjusts space between the facets
        strip.placement = "outside", #positions facet labels below x-axis labels
        strip.background = element_blank()) #transparent background for facet labels

plot