如何显示与所用变量不同的标签

How to display display another labels different from thoses of the variables used

您好,我想表示条形图,以便与同一功能系统相关的疾病以相同的方式着色。由于通过代码对类似疾病进行分组更容易,因此我这样做了。但是,我要显示的是疾病标签。但是我不能按标签对相似的疾病进行分组,因为标签没有任何共同点(在我的真实数据框中),而且我无法手动完成,因为我在大型数据库上工作。这就是我的数据库的样子。

ID=1:20
Hospital<-sample(c(rep("A",10),rep("B",10)))
Disease<-c("D1000",rep("D2001",2),rep("D2000",3),rep("D3000",4),
           rep("D3001",2),rep("D3003",4),rep("D4001",3),"D4002")
labels<-c("Infection",rep("Cancer.type1",2),rep("Cancer.type0",3),
          rep("Trauma.type0",4),rep("Trauma.type1",2),
          rep("Trauma.type3",4),rep("Heart.type1",3),"Heary.type2"  )
data<-data.frame(ID,Hospital,Disease,labels)
data$Disease<-as.factor(data$Disease)

下面是我如何绘制条形图。所有以 D4 开头的疾病都具有相同的 colors.All 以 D3 开头的疾病也具有相同的颜色。等等。现在我希望疾病标签出现在图表上而不是它们的代码上。

data%>%count(Disease)%>%
ggplot(aes(x=Disease,y=n))+
geom_col(aes(fill=substr(Disease,1,2)),show.legend = F)+
coord_flip()

您只需将 labels 添加到您的 count 函数,并以此为基础绘图:

data %>% 
  count(labels, Disease) %>%
  ggplot(aes(x = labels, y = n)) +
    geom_col(aes(fill = substr(Disease,1,2)), show.legend = FALSE) +
    coord_flip()

您可以使用 scale_x_discrete(labels= ...) 设置标签(因为您使用了 coord_flip,所以它是 x 而不是 y)。例如,参见 更改刻度线 部分 here。您必须为其提供一个命名向量,例如我在下面第一行中生成的向量:

labels <- setNames(labels, Disease)

data%>%count(Disease)%>%
  ggplot(aes(x=Disease,y=n))+
  geom_col(aes(fill=substr(Disease,1,2)),show.legend = F)+
  coord_flip() +
  scale_x_discrete(labels=labels)