我真的很感谢在这个情节上的一些帮助。我对R非常陌生,并且努力(在看了很多教程之后!)来理解如何绘制以下内容:
这是我的表The X axis is meant to have PatientID, the Y is cell counts for each patient
我已经设法为每个变量分别绘制了一个基本的图,例如:
This is for 2 of the variables
这给了我两个独立的图Total cell counts Cells counts for zone 1
我希望每个患者的所有数据都在1个graph...That均值上表示,将有4个条形(tot细胞计数和每个区域的细胞计数(1 - 3) )。
我不明白我是应该把它作为一个组合图来做,还是把这4个不同的图组合在一起?我也很困惑如何对此进行实际编码。我已经尝试过ggplot,并且我已经在R中完成了常规的Barplot (一次只能处理一个变量,但不确定如何处理多个变量)。在这里,一些非常循序渐进的帮助将非常受欢迎。提亚
发布于 2021-09-30 08:47:12
以下是使用tidyverse中的ggplot2和tidyr包完成此操作的一种方法。关键步骤是将您的数据从“宽”格式转换为“长”格式,以使其可用于ggplot2。之后,ggplot调用非常简单-如果你想在ggplot2中获得更多关于堆叠和条形图的解释,可以使用一个与你的例子几乎相同的例子来了解更多的信息here。
library(ggplot2)
library(tidyr)
# Reproducing your data
dat <- tibble(
patientID = c("a", "b", "c"),
tot_cells = c(2773, 3348, 4023),
tot_cells_zone1 = c(994, 1075, 1446),
tot_cells_zone2 = c(1141, 1254, 1349),
tot_cells_zone3 = c(961, 1075, 1426)
)
to_plot <- pivot_longer(dat, cols = starts_with("tot"), names_to = "Zone", values_to = "Count")
ggplot(to_plot, aes(x = patientID, y = Count, fill = Zone)) +
geom_bar(position="dodge", stat="identity")输出:

发布于 2021-09-30 09:11:53
感谢大家的帮助。我可以把情节做得如下所示:
首先,我根据导入到R中的数据创建了一个新表:
#Make new table of patientID and tot cell count
patientID <- c("a", "b", "c")
tot_cells <- c(tot_cells_a, tot_cells_b, tot_cells_c)
tot_cells_zone1 <- c(tot_cells_a_zone1, tot_cells_b_zone1, tot_cells_c_zone1)
tot_cells_zone2 <- c(tot_cells_a_zone2, tot_cells_b_zone2, tot_cells_c_zone2)
tot_cells_zone3 <- c(tot_cells_a_zone3, tot_cells_b_zone3, tot_cells_c_zone3)
tot_cells_table <- data.frame(tot_cells,
tot_cells_zone1,
tot_cells_zone2,
tot_cells_zone3)
rownames(tot_cells_table) <- c(patientID)然后我这样绘制,首先将data.frame转换为矩阵:
#Plot "Total Microglia Counts per Patient"
tot_cells_matrix <- data.matrix(tot_cells_table, rownames.force = patientID)
par(mar = c(5, 4, 4, 10),
xpd = TRUE)
barplot(t(tot_cells_table[1:3, 1:4]),
col = c("red", "blue", "green", "magenta"),
main = "Total Microglia Counts per Patient",
xlab = "Patient ID", ylab = "Cell #",
beside = TRUE)
legend("topright", inset = c(- 0.4, 0),
legend = c("tot_cells", "tot_cells_zone1",
"tot_cells_zone2", "tot_cells_zone3"),
fill = c("red", "blue", "green", "magenta"))该图如下所示:Barplot of multiple variables
再次感谢您为我指明了正确的方向!
https://stackoverflow.com/questions/69384152
复制相似问题