ggplot显示数据表的图表底部

时间:2018-09-17 10:58:07

标签: r ggplot2

我想在图的底部显示一个类似于此的数据表:

Sample Graph

我一直在尝试this中的代码,但该代码无法在我的RStudio版本1.1.383中运行。

该图的数据框为:

Pay.Quartiles = rep(c("lower", "lower.mid", "upper.mid", "upper"),2)
Gender = rep (c("Female", "Male"), each = 4)
Percentage = c(65.1,57.5,47.4, 41.3, 34.9, 42.5, 52.6, 58.7)

df = data.frame (Pay.Quartiles, Gender, Percentage)

1 个答案:

答案 0 :(得分:4)

结合一些数据处理(以获得更好的标签)和带有一些剥离位置调整的刻面应该可以解决问题:

library(hrbrthemes) # gitlab.com/hrbrmstr/hrbrthemes or github
library(ggplot2)

Pay.Quartiles <-  rep(c("Lower", "Lower Middle", "Upper Middle", "Upper"), 2)
Gender <-  rep(c("Female", "Male"), each = 4)
Percentage <-  c(65.1,57.5,47.4, 41.3, 34.9, 42.5, 52.6, 58.7)/100

xdf <- data.frame (Pay.Quartiles, Gender, Percentage, stringsAsFactors=FALSE)

xdf$lab <- sprintf("%s\n%s", Gender, scales::percent(Percentage))

ggplot(xdf) +
  geom_col(
    aes(lab, Percentage, fill = Gender), 
    width = 0.5, show.legend = FALSE
  ) +
  facet_wrap(
    ~Pay.Quartiles, scales = "free_x", nrow = 1, strip.position = "bottom"
  ) +
  hrbrthemes::scale_y_percent() +
  hrbrthemes::scale_fill_ipsum() +
  labs(x = NULL, y = NULL) +
  hrbrthemes::theme_ipsum_rc(grid = "Y") +
  theme(strip.placement = "outside") +
  theme(strip.text = element_text(hjust=0.5)) +
  theme(panel.spacing.x = unit(0.33, "lines"))

enter image description here