-
Hi DS team- I hope you're well! I am running a for loop which filters and plots my data according to 3 conditions (method, developmental stage, gene). I was wondering if there is a way to keep the scale of the histograms (the x and ylim) the same for all the plots of a single gene. E.g. all plots describing the expression level of gene x, (regardless of the developmental stage of the cell, or the method used), have the same limits. I'm hoping this will help me track how gene expression changes throughout different developmental stages. This is my current code: all_genes = unique(exonic_dataset_longer$Gene)
all_sorted = unique(exonic_dataset_longer$Sorted_Classification)
all_method = unique(exonic_dataset_longer$Rep)
library(ggplot2)
for (m in all_method ){
exonic_data_m = filter(exonic_dataset_longer, Rep == m)
for (s in all_sorted){
exonic_data_m_s = filter(exonic_data_m, Sorted_Classification == s)
for (g in all_genes){
exonic_data_m_s_g = filter(exonic_data_m_s, Gene == g)
p = ggplot(exonic_data_m_s_g, aes(Expr)) +
geom_histogram(fill="royalblue", alpha=0.6) +
ggtitle(paste0( g, " ", s, " ", m, ".png"))+
theme(axis.text.x=element_text(angle=45, hjust=1, vjust=1))
plot = p, width = 6, height=6)
}
}} Thank you so much for your insight and support- truly appreciate it! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi Zahra! Sure, there is a way! The way you specify an x-axis range in In case it wasn't clear, your current loop is like this: for (m in all_method ){
...
for (s in all_sorted){
...
for (g in all_genes){
}
}
}
so you should move the for (g in all_genes){
exonic_data_g = filter(exonic_data, Gene == g)
max_expr = exonic_data_g$Expr
for (s in all_sorted){
...
for (m in all_method){
exonic_data_m_s_g = ...
p = ggplot(exonic_data_m_s_g, aes(Expr)) +
geom_histogram(fill="royalblue", alpha=0.6) +
scale_x_continuous(limits = c(0, max_expr)) + # to keep the x axis constant for a given gene
ggtitle(paste0( g, " ", s, " ", m, ".png"))+
theme(axis.text.x=element_text(angle=45, hjust=1, vjust=1))
plot = p, width = 6, height=6)
}
}
}
Hope that solves your question! |
Beta Was this translation helpful? Give feedback.
Hi Zahra!
Sure, there is a way! The way you specify an x-axis range in
ggplot
is by using the family of functionsscale_x_*
, in this case you'll need to usescale_x_continuous()
. Since you'll want the same limits for each gene, you can move the inner-most loop to the top, so that you can calculate the range of a gene first, and then apply it to all plotsIn case it wasn't clear, your current loop is like this:
so you should move the
for (g in all_genes){
to the top. You can do the same thing you're doing of filtering dataframes sequentially to get a dataframe with only geneg
.Once you…