I have this data that describes the occurrence of some cell types, in responding patients vs non responsive patients for some drug:
> dput(cellsdata)
structure(list(response = c(1, 7, 2, 3, 4, 2, 1, 2, 1, 5, 5,
4, 2, 0, 0, 2, 0, 0, 1, 3, 1, 2, 1, 0, 4, 3, 2, 3, 1, 1, 5, 0,
2, 2, 5, 4, 4, 2), no_response = c(1, 0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 3, 2, 3, 2, 0, 3, 0, 0, 0, 1, 1, 0, 1, 4, 0, 0, 0,
0, 2, 1, 0, 0, 0, 0, 0)), class = "data.frame", row.names = c("Adipocytes",
"B-cells", "Basophils", "CD4 memory T-cells", "CD4 naive T-cells",
"CD4 T-cells", "CD4 Tcm", "CD4 Tem", "CD8 naive T-cells",
"CD8 T-cells", "CD8 Tcm", "Class-switched memory B-cells",
"DC", "Endothelial cells", "Eosinophils", "Epithelial cells",
"Fibroblasts", "Hepatocytes", "ly Endothelial cells", "Macrophages",
"Macrophages M1", "Macrophages M2", "Mast cells", "Melanocytes",
"Memory B-cells", "Monocytes", "mv Endothelial cells", "naive B-cells",
"Neutrophils", "NK cells", "pDC", "Pericytes", "Plasma cells",
"pro B-cells", "Tgd cells", "Th1 cells", "Th2 cells", "Tregs"
))
I want a bar plot, to look something like this, and I also need it to be in order, from the highest bin on the left to the right.
CodePudding user response:
I guess something like this. First convert the row names to a column. Then turn them into a factor whose levels are ordered according to the sum of your response
/ no_response
columns. Pivot to long format and use the new Response
column as the fill variable. The rest is just styling.
library(tidyverse)
cellsdata %>%
rownames_to_column("Cell") %>%
mutate(n = response no_response) %>%
arrange(-n) %>%
mutate(Cell = factor(Cell, Cell)) %>%
select(-n) %>%
pivot_longer(-Cell, names_to = "Response") %>%
ggplot(aes(Cell, value, fill = Response))
geom_col(position = "stack")
theme_light(base_size = 16)
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
scale_fill_manual(values = c("orange", "#3A43D8"),
labels = c("No response", "Response"), name = NULL)
CodePudding user response:
Using reshape2
with your data
df$row.names<-rownames(df)
long.df<-reshape2::melt(df,id=c("row.names"))
library(ggplot2)
ggplot(long.df, aes(
fill = variable,
y = value,
x = reorder(row.names, -value)
))
geom_bar(position = "stack", stat = "identity") labs(x = "row name")
theme(axis.text.x = element_text(
angle = 90,
vjust = 0.5,
hjust = 1
))
Output: