R ggplot2:将文本添加到geom_平铺
我需要显示聚类的结果。有关演示,请参见R ggplot2:将文本添加到geom_平铺,r,ggplot2,geom-text,R,Ggplot2,Geom Text,我需要显示聚类的结果。有关演示,请参见 library(ggplot2) df = data.frame(cluster=c(1,1,2,2,2,3),states=c("AB","IN","UN","CH","LO","OK")) p2<-ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+ geom_tile()+ geom_text(aes(label=cluster)) p2 库(ggplot2) df=data.f
library(ggplot2)
df = data.frame(cluster=c(1,1,2,2,2,3),states=c("AB","IN","UN","CH","LO","OK"))
p2<-ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(aes(label=cluster))
p2
库(ggplot2)
df=data.frame(集群=c(1,1,2,2,3),状态=c(“AB”,“IN”,“UN”,“CH”,“LO”,“OK”))
p2您可以使用函数reorder()
根据集群更改因子级别的顺序
现在使用新的dataframe添加标签
ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(data=df2,aes(y=pos,label=cluster))
另一种方法是使用缩放y\u离散
设置分幅的顺序,并在几何文字
上使用空白标签,使每个分幅只有一个标签
这可以做到:
ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(aes(label=c('1', '', '', '', '2', '3')))+
scale_y_discrete(limits=c("AB", "IN", "CH", "LO", "UN", "OK"))
注意,标签不会在群集中的偶数个元素的中间。它将位于您选择的位置。
1。可以通过对状态中的因子级别重新排序来解决。
ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(data=df2,aes(y=pos,label=cluster))
ggplot(df,aes(x=1,y=states,fill=factor(cluster)))+
geom_tile()+
geom_text(aes(label=c('1', '', '', '', '2', '3')))+
scale_y_discrete(limits=c("AB", "IN", "CH", "LO", "UN", "OK"))