如何使用ggplot标记特定的y轴

时间:2018-03-10 20:13:01

标签: r ggplot2 axis-labels

我有这样的数据

# Generation of dataframe
name_genes <- paste(rep("GEN", 20), LETTERS[1:20], sep="_") # rows
name_patients <- paste(rep("PATIENT", 20), seq(1,20,1), sep="_") # columns
value_expression <- data.frame(genes = name_genes, 
                               matrix(rnorm(400, 2, 1.8),nrow = 20, ncol = 20))
names(value_expression)[2:21] <- name_patients
df_heatmap <- melt(value_expression, id.vars = "genes")
names(df_heatmap)[2:3] <- c("patient", "expression_level")

我试图只提及特定的标签

然后我可以像这样绘制它

ggplot(df_heatmap, aes(patient, genes )) +
  geom_tile(aes(fill = expression_level), color = "white") +
  scale_fill_gradient(low = "white", high = "steelblue") +
  ylab("List of genes ") +
  xlab("List of patients") +
  theme(legend.title = element_text(size = 10),
        legend.text = element_text(size = 12),
        plot.title = element_text(size=16),
        axis.title=element_text(size=14,face="bold"),
        axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(fill = "Expression level")

我只希望标签为

GEN_R
GEN_O
GEN_F
GEN_E
GEN_A

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您必须使用scale_y_discrete()重写y缩放标签以执行您想要的操作。

在致电ggplot()之前,添加

nameskeep = c(1,5,6,15,18) # This is the indices of the genes you want to keep
labels = rep("",20)        # This is a vector containing empty strings
labels[nameskeep ] = name_genes[nameskeep] # which are replaced with the genes you which to keep

然后使用添加了+ scale_y_discrete

绘制图形
ggplot(df_heatmap, aes(patient, genes )) +
  geom_tile(aes(fill = expression_level), color = "white") +
  scale_fill_gradient(low = "white", high = "steelblue") +
  scale_y_discrete(labels=labels) + #added line here
  ylab("List of genes ") +
  xlab("List of patients") +
  theme(legend.title = element_text(size = 10),
        legend.text = element_text(size = 12),
        plot.title = element_text(size=16),
        axis.title=element_text(size=14,face="bold"),
        axis.text.x = element_text(angle = 90, hjust = 1)) +
  labs(fill = "Expression level")