我需要为x轴上不同列的两种动物创建条形图。
为了让它更清晰
我的数据是这样的:
ID, Type, Baseline_Respiratory_Rate (BLRR), Day3_RR, Day7_RR, Day14_RR
1 Stroke 233
2 Stroke 200
3 Sham 250
4 Sham 450
5 Sham 350
6 Stroke 234
7 Stroke 180
8 Sham 300
9 Sham 250
10 Stroke 166因此,我需要在x轴上绘制不同日期的平均呼吸频率(Baseline,Day3,Day7,Day4),每天都有两个条形图,一个用于中风,另一个用于假,所有这些都在同一个图上。
作为一个初学者,我想不出一种方法来做到这一点,我正试图系统地学习R,但我现在需要学习这个。
非常感谢
发布于 2021-04-09 15:15:18
在您的数据中,缺少第3天以后的值。因此,我将使用以下较小的数据集进行说明。
ID;Type;baseline;day1
1;Stroke;233;133
2;Stroke;200;100
3;Sham;250;200
4;Sham;450;300
5;Sham;350;200
6;Stroke;234;230
7;Stroke;180;190
8;Sham;300;290
9;Sham;250;150
10;Stroke;166;200把这个放在一个叫做“动物”的数据框里。现在
tmp<-aggregate(animals[,3:4],list(type=animals$Type),mean)给出每天的平均呼吸次数和类型。要获得条形图,请使用
barplot(as.matrix(tmp[2:3]),beside=TRUE)您可以通过添加图例、轴标签等来使柱状图更美观一些。我把这个留给你了。
发布于 2021-04-09 15:51:42
以下是针对假数据的完整解决方案:
library(tidyverse)
# add fake data for Day 3, 7, 14
set.seed(123)
Day3_RR <- sample(166:450,10)
Day7_RR <- sample(166:450,10)
Day14_RR <- sample(166:450,10)
BLRR <- c(233, 200, 250, 450, 350, 234, 180, 300, 250, 166)
Type <- c("Stroke", "Stroke", "Sham", "Sham", "Sham", "Stroke", "Stroke", "Sham", "Sham", "Stroke")
ID <- 1:10
df <- cbind(ID, Type, BLRR, Day3_RR, Day7_RR, Day14_RR)
# tweak dataframe, to longformat with `pivot_longer` from `tidyr` package
df <- df %>%
as_tibble() %>%
type.convert(as.is = T) %>%
pivot_longer(
cols= c(starts_with("Day"), BLRR),
names_to = "time",
values_to = "RR"
) %>%
mutate(time = factor(time, levels = c("BLRR", "Day3_RR", "Day7_RR", "Day14_RR"))) %>%
group_by(Type, time) %>%
dplyr::summarise(avg_RR = mean(RR, na.rm=TRUE)) %>%
ungroup()
ggplot(df, aes(x=time, y=avg_RR, fill = Type)) +
geom_bar(stat="identity", position = "dodge") +
geom_text(aes(label=round(avg_RR)), position=position_dodge(width=0.9), vjust=-0.25) +
scale_fill_brewer(palette = "Dark2") +
theme_bw()

https://stackoverflow.com/questions/67015821
复制相似问题