我想将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")
如何在不更改数据框的情况下做到这一点?
这是我的数据框示例:
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))
答案 0 :(得分:4)
您似乎想将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")
请注意aes(num, factor(sample_type), ...)
将sample_type转换为因子,然后通知scale_y_discrete
来控制这些级别的标签。