tidyverse / ggplot2

An implementation of the Grammar of Graphics in R
https://ggplot2.tidyverse.org
Other
6.5k stars 2.02k forks source link

How to set the color grouping of facet blocks #6141

Closed Fugwaaaa closed 1 minute ago

Fugwaaaa commented 3 hours ago

I modify the plot_genes_in_pseudotime function so that it can group the color of line for different cell types. Based on this, I also carry out facets of different gene. Now I want gene to group the color of facets according to its corresponding pathway. But since each gene has a different Y-axis after drawing, is there any way to set the block color of the facet? This is my script

q <- ggplot(aes(Pseudotime, expression), data = epp) + geom_line(aes(x = Pseudotime, y = expectation, color = Celltype4), data = ep) + geom_rect( data=epp, aes(xmin=-Inf, xmax=Inf, ymin=Inf-5, ymax=Inf+5, fill=Description), alpha=0.4) + scale_color_manual(values = color_mapping) + scale_y_log10() + coord_cartesian(clip="off")+ facet_wrap(~feature_label, nrow = 7, ncol = 8, scales = "free_y") + scale_fill_manual(values = c("nuclear envelope" = "green", "nuclear speck" = "red", "focal adhesion" = "blue", "vacuolar membrane" = "black"))+ expand_limits(y = c(min_expr, 1)) + ylab("Relative Expression") + xlab("Pseudo-time")+ theme_bw()+ theme( strip.background = element_rect(fill=NA), strip.text = element_text(face="bold") ) q

Fugwaaaa commented 3 hours ago

I find a code like this,but his data is consistent with the Y-axis coordinates. library(ggplot2) library(tidyr) library(dplyr)

dataset for plotting

df <- mtcars %>% gather(-mpg, key = "var", value = "value")

dataset for facet label colors

hacky_df <- data.frame( var = c("am", "carb", "cyl", "disp", "drat", "gear", "hp", "qsec", "vs", "wt"), var_color = c("area", "indus", "indus", "bat", "bat", "bat", "area", "indus", "vege", "vege") )

plot code

plot_new <- ggplot(df) + # don't specify x and y here. Otherwise geom_rect will complain. geom_rect( data=hacky_df, aes(xmin=-Inf, xmax=Inf, ymin=36, ymax=42, # totally defined by trial-and-error fill=var_color, alpha=0.4)) + geom_point(aes(x = value, y = mpg)) +
coord_cartesian(clip="off", ylim=c(10, 35)) + facet_wrap(~ var, scales = "free") + scale_fill_manual(values = c("area" = "green", "bat" = "red", "vege" = "blue", "indus" = "black")) +

theme_bw() + theme( strip.background = element_rect(fill=NA), strip.text = element_text(face="bold") )`

1729138735507

https://stackoverflow.com/questions/70841252/how-to-specify-different-background-colors-for-each-facet-label-in-ggplot2

teunbrand commented 1 minute ago

Hi there, we use this issue tracker for collecting bug reports and feature requests. Your post contains neither and seems like you're looking for help with a problem. Instead of posting here, we recommend you seek help elsewhere, like stack overflow or the Posit community.