library(ggplot2)
testA =matrix(runif(n=380,0,1),20,19)
colnames(testA)=paste0('cancer',LETTERS[1:19])
row.names(testA) = paste0('sample',1:20)
library(reshape2)
dataA = melt(testA,
             varnames = c('sample','cancer'),
             value.name = 'exp')

# Function to get colors for labels
get_label_colors <- function(labels,pal="Set2",labels_unique=NULL,alpha=1){
  if (is.null(labels_unique)){
    labels_unique <- sort(unique(labels))
  }
  palette <- RColorBrewer::brewer.pal(n=RColorBrewer::brewer.pal.info[pal,"maxcolors"],pal)
  
  lab2col <-list()
  i <- 1
  for (lab in labels_unique) {
    lab2col[[lab]] <- grDevices::adjustcolor(palette[(i-1)%%length(palette) + 1],alpha)
    i <- i+ 1 
  }
  
  colors <- c()
  for (lab in labels){
    colors <- c(colors,lab2col[[lab]])
  }
  
  colors
}

# Get colors for the cancer categories
colors = get_label_colors(unique(dataA$cancer))

# Create the violin plot
p1 <-ggplot(dataA,aes(cancer,exp,fill=cancer))+
  geom_violin()+  
  coord_flip()+  
  scale_fill_manual(values = colors)+  
  stat_summary(fun=mean,geom = "point",
               shape = 19, size = 2, color = "black")+  
  theme_bw()+  
  geom_hline(aes(yintercept=0.6),colour="#565354",linetype="dashed")+  
  geom_hline(aes(yintercept=0.3),colour="#565354",linetype="dashed")+  
  xlab('')+  
  ylab('A indicator\nindicator A')+  
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.text.y =  element_text(size = 12,
                                    face = "bold"),
        legend.title = element_blank(),
        legend.position = 'none')

# Create a theme to remove y-axis elements
remove_y <- theme(
  axis.text.y = element_blank(),
  axis.ticks.length.y = element_blank(),
  axis.title.y = element_blank()
)

# Create a list of plots with different y-axis configurations
p <- list(
  p1,
  p1 + remove_y,
  p1+remove_y,
  p1+remove_y
)

# Arrange the plots using patchwork
library(patchwork)
wrap_plots(p,nrow=1)

# Save the plot
ggsave('3.complex_violin.pdf',width = 8,height = 6)


# **Error Resolution**

# 1. **Error: "Error in RColorBrewer::brewer.pal.info[pal, "maxcolors"] : subscript out of bounds"**

This error occurs if the specified color palette name (pal) is not found in the RColorBrewer library. To resolve this, ensure that the palette name exists. In this code, we replaced "Dark2" with "Set2", which is a valid palette name.

# 2. **Error: "Error in RColorBrewer::brewer.pal(n = RColorBrewer::brewer.pal.info[pal,  : could not find function "brewer.pal""**

This error arises if the RColorBrewer library is not loaded. You need to import the library before using its functions. Add this line at the beginning of your code:

```r
library(RColorBrewer)

This code provides a comprehensive solution, addressing the errors you encountered, and ensuring a visually appealing violin plot with customized colors and legends. Make sure to install the required packages (ggplot2, reshape2, RColorBrewer, and patchwork) before running the code.

R ggplot2 Violin Plot with Custom Colors and Legends

原文地址: https://www.cveoy.top/t/topic/nJVQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录