如何显示与所使用的变量不同的另一个标签。

问题描述 投票:0回答:1

你好,我想用柱状图表示,使与同一功能系统相关的疾病以同样的方式着色。由于通过代码将类似的疾病分组比较容易,我已经这样做了。 然而,我想显示的是疾病标签。但是,我不能通过它们的标签对相似的疾病进行分组,因为这些标签没有任何共同点(在我的真实数据框中),而且由于我在一个大型数据库中工作,我不能手动进行分组。这是我的数据库可能的样子。

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开头的疾病都有相同的颜色,所有以D3开头的疾病也有相同的颜色。以此类推。现在我想让疾病标签出现在图表上,而不是它们的代码。

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

enter image description here

r label bar-chart
1个回答
4
投票

你只需要添加 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()

enter image description here


3
投票

使用 scale_x_discrete(labels= ...) 您可以设置标签(因为您使用了 coord_flip它是 x 而不是 y). 例如,见 更改勾号此处. 你必须为它提供一个命名的向量,比如我在下面第一行生成的向量。

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)
© www.soinside.com 2019 - 2024. All rights reserved.