我想翻转立桩条形图的方向,使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,但是类别变量仍然在底部。
任何帮助将不胜感激。
1条答案
按热度按时间n6lpvg4x1#
要将类别放在左侧,请将
ncol=1
设置为facet_wrap
和strip.position="left"
。对于年份,将factor(y)
Map到y
上,将Sales
Map到x
上。要将标签Map到geom_text
中的label
aes上,请执行以下操作: