如何在ggplot中构建具有两个连续列的堆叠条形图

问题描述 投票:0回答:1

我想创建一个水平排列的堆积条形图。 条形图应显示“cost1”和“cost2”的总和,并在每个条形图的末尾有一个标签。下面,您可以看到代码,但我与它堆叠在一起,因为它没有排名并且标签编号不起作用。我使用了 pivot_longer 函数,但也许这不是重新排列数据集的正确方法。我确信有一种简单明了的方法可以做到这一点。你能帮我吗?

library(tidyverse)

data_test <- tribble(
  ~name, ~cost1, ~cost2, ~totalCost,
  "John", 10, 40, 50,
  "Martin", 21, 35, 56,
  "Michael", 15, 80, 95,
  "Dave", 28, 40, 68,
  "Dan", 18, 35, 53
)
View(data_test)

df <- data_test %>%
  pivot_longer(cols = c("cost1", "cost2"),
               names_to = "cost",
               values_to = "value")

ggplot(df, aes(x=name, y=value, fill = cost)) +
  geom_bar(position = "fill", stat = "identity") +
  coord_flip()

enter image description here

r ggplot2 bar-chart stacked-bar-chart
1个回答
0
投票

我想你正在寻找这个:

ggplot(df, aes(y=name, x=value, fill = cost)) +
  coord_cartesian(clip = "off") +
  geom_bar(position = "stack", stat = "identity") +
  geom_text(
    aes(label = after_stat(x), group = name), 
    stat = 'summary', fun = sum, hjust = -0.5
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.