我有一个数据框,其中包含文章名称、每篇文章的总体样本数、药物的响应者数量和无响应者数量。总共有 9 篇文章:
Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
"Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)
MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)
Run Code Online (Sandbox Code Playgroud)
我需要制作一个条形图,其中 x 轴上为文章名称,y 轴上为总体样本数,并为每个 bin 着色,例如,对于每篇文章,响应者为蓝色,非响应者为红色。
我构建了一个条形图,我只是不知道在填充段中输入什么:(这里我只是输入了 No_Benefit 列,但我知道这是一个错误的填充)
myplot <- ggplot(MyData, aes(x = Articles, y = Samples_number, fill= No_Benefit)) + theme_bw() + geom_col(position = "stack")
print(myplot)
Run Code Online (Sandbox Code Playgroud)
我认为主要问题在于数据帧的格式;您的数据采用“宽”格式,但 ggplot2 使用“长”格式效果更好。pivot_longer()您可以使用tidyr 包中的函数将数据框从“宽”转换为“长” ,例如
library(ggplot2)
library(tidyr)
Articles <- c("Nadeem Riaz", "David Braun","immotion150", "IMVIGOR210", "Alexander Lozano",
"Van Allen", "Alexandra Pender", "David Lui", "Jae Cho")
Samples_number <- c(49, 311, 247, 298, 47, 39, 82, 121, 16)
With_Benefit <- c(26, 89, 168, 131, 27, 13,17,65, 5)
No_Benefit <- c(13, 102, 79, 167, 20, 26, 65, 56, 11)
MyData <- data.frame(Articles, Samples_number, With_Benefit, No_Benefit)
MyData_long <- pivot_longer(MyData, -c(Articles, Samples_number), names_to = "response")
ggplot(MyData_long, aes(x = Articles, y = Samples_number, fill= response)) +
theme_bw() +
geom_col(position = "stack")
Run Code Online (Sandbox Code Playgroud)

由reprex 包于 2022 年 2 月 9 日创建(v2.0.1)