【发布时间】:2020-11-12 10:04:40
【问题描述】:
以下是我用来绘制分组条形图的代码: 如果我正在使用,我可以保留统一的条形宽度,但无法删除缺失数据的空白空间
geom_bar(stat="identity",position=position_dodge(preserve = "single"),na.rm = TRUE,width = 0.9).
如果我不使用上述命令,我将无法保留条形宽度,尽管我可以删除空格。
library(ggplot2)
library(reshape2)
library(readxl)
df <- read_excel("Documents/Analysis.xlsx")
ggplot(data = df, aes(x = Cell_type, y = Percentage_of_cell, fill = Sample_id, na.rm = TRUE),
position = position_dodge(preserve = "single", padding = 0)) +
geom_bar(stat = "identity", position = position_dodge(preserve = "single"), na.rm = TRUE, width = 0.9)+
theme_bw() +
scale_fill_manual(values=c("darkgoldenrod3","darkolivegreen"))+
theme(axis.text.x = element_blank(),
axis.text.y = element_text(color="black", angle = 90, hjust = 1, size = 12, face = "bold"),
axis.title.y = element_text( size = 12, angle = 90, hjust = .5, vjust = .5, face = "bold"),
legend.text = element_text(size = 12, face = "bold"),
axis.ticks.x = element_blank())+
labs(fill="") +
xlab("") +
ylab("% of Cell_type\n") +
facet_grid(~Cell_type),
scales = "free_x", space = "free_x")+
theme(plot.margin = unit(c(1,1,1.5,1.2),"cm"))+
theme(strip.text = element_text(colour = 'black', face="bold", size=11))+
theme(legend.position = "bottom")
这里是df:
Sample_id Cell_type Percentage_of_cell
Sample1 Cell1 4.701222662
Sample2 Cell1 0.829875519
Sample2 Cell2 5.526216522
Sample1 Cell3 1.980368521
Sample2 Cell3 20.50169747
Sample1 Cell4 22.75701739
Sample2 Cell4 21.3504338
Sample1 Cell5 15.00774927
Sample2 Cell5 9.430403621
Sample1 Cell6 7.465128293
Sample1 Cell7 0.602720854
Sample2 Cell7 1.772915881
Sample1 Cell8 44.07611503
Sample2 Cell8 40.58845719
Sample1 Unassigned 3.409677975
我是 R 新手,请帮忙指出我哪里出错了,或者是否有其他解决方案。
【问题讨论】:
-
如果您以这种方式编辑
df:tidyr::complete(df, Sample_id, tidyr::nesting(Cell_type), fill = list(Percentage_of_cell = 0)),您会得到预期的结果吗? [问题出在 Cell 2 上,对吧?] -
我也试过了。但是它对我不起作用,问题在于 Cell2、Cell6 和 Unassigned,其中我只有一个样本的数据。
-
那我不明白你的预期结果。当它单独时,你想要列在中心吗?
-
是的,我想在 Cell2 的中心,Cell6 刻面而不是 Sample1 和 Sample2 空间中。
标签: r ggplot2 facet-grid