ggplot加长x标度以显示空因子水平

时间:2018-09-23 13:15:42

标签: r ggplot2

我想绘制一个在某些因子水平上具有0个观察值的因子变量。

我可以使用geom_bar(drop=false)成功绘制此图,但是x轴太短:

enter image description here

我希望x轴及其刻度线具有相同的长度/几何形状,就像我观测到的水平分别为0、3和4:

enter image description here

如上图所示,级别0和4有足够的空间,刻度线在正确的位置。即使我在0、3和4级没有观察到,我也希望这种行为。


以下是生成有问题的情节的代码:

# create the data frame
df = data.frame( species = c(1,2,1,1,2,2,2,2,1,1,2,1,2,2,1))

# set the species as factors
df$species = as.factor(df$species)

# we didn't see species 0, 3 or 4 but we still want to plot them
df$species = fct_expand(df$species,"0","3","4")

levels((df$species))

# re order the levels
df$species = factor(df$species,levels(df$species)[c(3,1,2,4,5)])

#check the levels look ok
table(df$species)

# plot
ggplot(data = df) + 
  scale_x_discrete(name = "species", expand = c(0, 0), drop = FALSE) +
  geom_bar(aes(x = species), stat = "Count", colour = "black", fill = "white", width = 1) 

我尝试将xlimbreaks修改为无效

谢谢

0 个答案:

没有答案