R语言 具有嵌套分组变量的多行轴标签,用于添加了水平条和值的桩标图

tag5nh1u  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(97)

我想翻转立桩条形图的方向,使Sales变量位于x轴上,Year和类别(Clothing、Electronics和Food)位于y轴上。此外,我想显示每个押入条形图的销售价值数字。

下面是一些虚拟代码

data2 <- read.table(text = "Product Category Year Sales
               A Clothing 2017 100
               A Clothing 2018 120
               A Electronics 2017 150
               A Electronics 2018 200
               A Food 2017 50
               A Food 2018 80
               B Clothing 2017 80
               B Clothing 2018 90
               B Electronics 2017 100
               B Electronics 2018 120
               B Food 2017 70
               B Food 2018 100", header=TRUE)

p2 <- ggplot()
p2 + geom_bar(data = data2, aes(x = Year, y = Sales, fill = Product), stat = "identity") +
  facet_wrap(vars(Category), strip.position = "bottom", scales = "free_x") +
  geom_text(size = 3, position = position_stack(vjust = 0.5)) +
  theme(panel.spacing = unit(0, "lines"),
        strip.background = element_blank(),
        axis.line = element_line(colour = "grey"),
        panel.grid.major.y = element_line(colour = "grey"),
        strip.placement = "outside",
        axis.text.x = element_text(angle = 90, hjust = 1),
        axis.title.x = element_blank(),
        panel.background = element_rect(fill = 'white', colour = 'white'))

我尝试使用coord_flip,但是类别变量仍然在底部。
任何帮助将不胜感激。

n6lpvg4x

n6lpvg4x1#

要将类别放在左侧,请将ncol=1设置为facet_wrapstrip.position="left"。对于年份,将factor(y)Map到y上,将SalesMap到x上。要将标签Map到geom_text中的label aes上,请执行以下操作:

library(ggplot2)

ggplot(data2, aes(y = factor(Year), x = Sales, fill = Product)) + 
  geom_col() +
  geom_text(aes(label = Sales), size = 3, position = position_stack(vjust = 0.5)) +
  facet_wrap(vars(Category), strip.position = "left", ncol = 1) +
  theme(
    panel.spacing = unit(0, "lines"),
    strip.background = element_blank(),
    axis.line = element_line(colour = "grey"),
    panel.grid.major.x = element_line(colour = "grey"),
    strip.placement = "outside",
    panel.background = element_rect(fill = "white", colour = "white")
  ) +
  labs(y = NULL)

相关问题