在 R 中使用 ggplot2 更改 x 标签

Changing the x lables using ggplot2 in R

我有这些数据并使用条形图绘制它。我想更改 x 标签以使其简单,

data_bayes <- read.table(text="
Estimation,Cell types,Total
No rank,Cell type 0 ,3468
No rank,Cell type 1 ,3468
No rank,Cell type 2 ,3468
No rank,Cell type 3 ,3468
No rank,Cell type 4 ,3468
No rank,Cell type 5 ,3468
No rank,Cell type 6 ,3468
No rank,Cell type 7 ,3468
No rank,Cell type 8 ,3468
No rank,Cell type 9 ,3468
Best three rank,Cell type 0 ,3
Best three rank,Cell type 1 ,3419
Best three rank,Cell type 2 ,130
Best three rank,Cell type 3 ,0
Best three rank,Cell type 4 ,538
Best three rank,Cell type 5 ,63
Best three rank,Cell type 6 ,3417
Best three rank,Cell type 7 ,2296
Best three rank,Cell type 8 ,536
Best three rank,Cell type 9 ,2
", header=TRUE, sep=",")

我用这段代码来获取剧情

ggplot(data_bayes, aes(x=Cell.types, y=Total, fill=Estimation)) + scale_fill_manual(breaks = c("Best three rank", "No rank"), 
                   values=c("green", "red")) +
geom_bar(stat="identity", position="dodge")+
theme(axis.text.x = element_text(angle = 90)) + scale_x_discrete(
"Cell types",
labels = c(
  "Cell type 0" = "0",
  "Cell type 1" = "1",
  "Cell type 2" = "2",
  "Cell type 3" = "3",
  "Cell type 4" = "4",
  "Cell type 5" = "5",
  "Cell type 6" = "6",
  "Cell type 7" = "7",
  "Cell type 8" = "8",
  "Cell type 9" = "9"
)
)

会导致这个情节

我已经使用参数 scale_x_discrete 将标签从单元格类型 0 更改为 0 等。但是,它并没有改变并且保持不变。为什么会这样?如何解决?

实现此目的的一种方法是:

  1. 我们在绘制之前创建一个标签列label_cell.types

  2. 然后分解它并绘制

library(tidyverse)

data_bayes %>% 
  mutate(label_cell.types = parse_number(Cell.types)) %>% 
  ggplot(aes(x=factor(label_cell.types), y=Total, fill=Estimation)) + 
  scale_fill_manual(breaks = c("Best three rank", "No rank"), values=c("green", "red")) +
  labs(x = "Cell types")+
  geom_bar(stat="identity", position="dodge")