我想重命名 y 轴刻度,而不是 1 - 到“国家”,2 - 到“城市”,3 - 到“所有”。我找不到办法做到这一点。我有以下脚本:
ggplot(test_df, aes(num, sample_type, fill = exist)) +
geom_tile(width=0.9, height=0.9,color = "gray")+
scale_fill_gradientn(colours = c("white", "lightgreen"), values = c(0,1))+
theme(axis.text.x = element_text(angle = 90, hjust = 1),
legend.position="none")+
scale_x_discrete(position = "top") + labs(x = "", y= "Sample Type")
Run Code Online (Sandbox Code Playgroud)
如何在不更改数据框的情况下做到这一点?
这是我的数据框示例:
test_df <- data.frame(
num = c("num1","num1","num1","num2","num2","num2","num3","num3","num3"),
sample_type = c(1,2,3,1,3,2,3,1,2),
exist = c(1,0,0,1,1,0,1,0,0))
Run Code Online (Sandbox Code Playgroud)
看起来您想将 Y 值视为非创造值,而不是数字。解决这个问题的最简单方法是将数字作为一个因子。你可以做
ggplot(test_df, aes(num, factor(sample_type), fill = exist)) +
geom_tile(width=0.9, height=0.9,color = "gray")+
scale_fill_gradientn(colours = c("white", "lightgreen"), values = c(0,1))+
theme(axis.text.x = element_text(angle = 90, hjust = 1),
legend.position="none")+
scale_y_discrete(labels=c("1"="country","2"="city", "3"="all")) +
scale_x_discrete(position = "top") + labs(x = "", y= "Sample Type")
Run Code Online (Sandbox Code Playgroud)
请注意aes(num, factor(sample_type), ...)将 sample_type 转换为因子,然后scale_y_discrete控制这些级别的标签。