R语言 ggplot水平堆叠条形图的函数

xpcnnkqh  于 2023-03-10  发布在  其他
关注(0)|答案(1)|浏览(129)

我试图创建一个水平堆叠酒吧,但无法做到这一点,也希望使酒吧动态一样(水平,垂直)对齐。
我也想显示N与标签一样,如下图所示。

proba <- data.frame(PartnerName = c("China", "Brazil", "Argentina", "UE", "US"), Food = c("12%","22%","36%","40%","51"), Machinery = c("91%","78%","64%","60%","49%"), Total = c(26,28,43,34,25))
graph_data <- proba %>% select(-Total)
graph_data %>%  
  pivot_longer(-PartnerName)  %>% 
  ggplot(aes(x=PartnerName, y=value, fill=name))+
  geom_bar(width = 0.9,stat="identity",position = "stack")
46scxncf

46scxncf1#

更新:带有一些解释的代码(删除了coord_flip),如@tjebo建议:

1.我们使用mutatepaste0为标签创建label_x
1.使用parse_number()(我最喜欢的函数),我们从xx%中提取数字。
1.使用pivot_longer()以长格式获取数据(长格式是ggplot 2的首选格式)
1.使用geom_text,我们将百分比数字添加到条形图中。
1.一些调整:将图例移至底部,删除标签x和y轴,并将背景留空。

library(dplyr)
library(readr) # parse_number()
library(ggplot2)
library(tidyr) # pivot_longer()
proba %>%  
  mutate(label_x = paste0(PartnerName, " N=", Total),
         across(c(Food, Machinery), parse_number)) %>% 
  arrange(Machinery) %>% 
  pivot_longer(c(Food, Machinery)) %>% 
  ggplot(aes(x=value, y=label_x, fill=name))+
  geom_col(width = 0.5, position = position_stack())+
  geom_text(aes(label = paste0(value, "%")), position = position_stack(0.5)) +
  scale_fill_manual(values = c("orange", "steelblue"))+
  labs(x="", fill="", y="")+
  theme_classic()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        legend.position = "bottom")

数据:

structure(list(PartnerName = c("China", "Brazil", "Argentina", 
"UE", "US"), Food = c("9%", "22%", "36%", "40%", "51"), Machinery = c("91%", 
"78%", "64%", "60%", "49%"), Total = c(26, 28, 43, 34, 25)), class = "data.frame", row.names = c(NA, 
-5L))

**第一个答案:**大概是这样的:

小心中国91%和12%不是100%

proba %>%  
  mutate(label_x = paste0(PartnerName, " N=", Total),
         across(c(Food, Machinery), parse_number)) %>% 
  arrange(Machinery) %>% 
  pivot_longer(c(Food, Machinery)) %>% 
  ggplot(aes(x=label_x, y=value, fill=name))+
  geom_col(width = 0.5, position = position_stack())+
  geom_text(aes(label = paste0(value, "%")), position = position_stack(0.5)) +
  scale_fill_manual(values = c("orange", "steelblue"))+
  labs(x="", fill="", y="")+
  coord_flip()+
  theme_classic()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        legend.position = "bottom")

相关问题