如何使用 ggplot 在 r 中创建堆积条形图

How to create a stacked bar chart in r with ggplot

我的数据是:



positive <- c("21", "22", "33", "21", "27") ##Percentage
negative<- c("71", "77", "67", "79", "73")  ##Precentage 
sample <- c("Hr", "Fi", "We", "Pa", "Ki")
mydata <- data.frame(positive , negative, sample)

我想创建一个堆叠条形图,显示样本变量中每个类别的正百分比和负百分比。我试过这个:

ggplot(mydata) +
  geom_bar(aes(x = sample, fill = positive))

但没有成功。 对不起,如果问题看起来很基本。我几周前开始使用 R。

您需要先将数据转换为长格式(整洁格式)。然后,我们可以指定x(sample)、y(value)和fill(name)条件。

library(tidyverse)

mydata %>%
  pivot_longer(-sample) %>%
  ggplot(aes(fill = name, y = value, x = sample)) +
  geom_bar(position = "stack", stat = "identity")

输出

这可能符合您的目的:

library(tidyverse)
mydata %>% pivot_longer(cols = !sample, names_to = "status", values_to = "percentage") %>% 
 ggplot(aes(fill = status, x = sample, y = percentage)) + 
 geom_bar(position = "stack", stat = "identity")

结果:

这是另一种方法,使用 values_transform 获取数字类型,然后使用 geom_colposition_fill 以及百分比特征:

library(dplyr)
library(tidyr)
library(ggplot)
library(scales)

mydata %>% 
  pivot_longer(
    cols = -sample,
    names_to = "status",
    values_to = "percentage", 
    values_transform = list(percentage = as.integer)
  ) %>% 
  ggplot(aes(x = sample, y=percentage, fill=status))+
  geom_col(position = position_fill()) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = percentage),
            position = position_fill(vjust = .5))

另一种解决方法ios使用了side-by-side吧。

示例数据:

values <- c(21, 22, 33, 21, 27, -71, -77, -67, -79, -73) ##Percentage
sample <- factor(c("Hr", "Fi", "We", "Pa", "Ki"))
mydata <- data.frame(values, sample)

示例代码:

(ggplot(mydata, aes(x = sample, y = values)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    color = "white", fill = "lightblue") +
  coord_flip())+
  labs(x="Sample",y="Percentage")+
  theme_bw()

剧情:

剧情:

显示值的示例代码:

(ggplot(mydata, aes(x = sample, y = values)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    color = "white", fill = "lightblue"
  ) +
    geom_text(aes(label = values))+
  coord_flip())+
  labs(x="Sample",y="Percentage")+
  theme_bw()

或者,如果您想要为正条和负条着色不同

(ggplot(mydata, aes(x = sample, y = values)) +
  geom_bar(
    stat = "identity", position = position_stack(),
    fill= ifelse(mydata$values < 0,"#ffcccb","lightblue")
  ) +
    geom_text(aes(label = values))+
  coord_flip())+
  labs(x="Sample",y="Percentage")+
  theme_bw()