ggplot不会绘制缺失的类别

时间:2016-08-23 17:36:38

标签: r ggplot2

我正在努力与ggplot(我一直这样做)。关于强制ggplot在图例中包含零值类别有很多非常类似的问题 - herehere(例如)。但是我(认为我)对scale_x_discrete和scale_fill_manual的所有麻烦都没有帮助的要求略有不同。

要求:正如您所见;右侧的图在TM = 5类别中没有数据 - 因此缺失。我需要的是正确的情节,在轴上显示类别5,但显然没有点或框。

enter image description here

当前绘图脚本

TypeError: file() argument 1 must be encoded string without NULL bytes, not str

尝试解决方案

  1. #data plotData <- data.frame("TM" = c(3,2,3,3,3,4,3,2,3,3,4,3,4,3,2,3,2,2,3,2,3,3,3,2,3,1,3,2,2,4,4,3,2,3,4,2,3), "Score" = c(5,4,4,4,3,5,5,5,5,5,5,3,5,5,4,4,5,4,5,4,5,4,5,4,4,4,4,4,5,4,4,5,3,5,5,5,5)) #vars xTitle <- bquote("T"["M"]) v.I <- plotData$TM depVar <- plotData$Score #plot p <- ggplot(plotData, aes_string(x=v.I,y=depVar,color=v.I)) + geom_point() + geom_jitter(alpha=0.8, position = position_jitter(width = 0.2, height = 0.2)) + geom_boxplot(width=0.75,alpha=0.5,aes_string(group=v.I)) + theme_bw() + labs(x=xTitle) + labs(y=NULL) + theme(legend.position='none', axis.text=element_text(size=10, face="bold"), axis.title=element_text(size=16)) 缩放(由@Jarretinha here建议)完全填充边距和x轴标签

    drop=False

  2. enter image description here

    1. 遵循here中的逻辑并手动设置> plot + scale_x_discrete(drop=FALSE) + scale_fill_manual(drop=FALSE)中的标签不执行任何操作,并从上面的示例中生成相同的右侧图。

      scale_fill_manual

    2. 使用此逻辑并使用{​​{1}}尝试某些操作会导致x轴上的类别名称发生更改,但第五个仍然缺失,并且边距(作为尝试1)再次被重复。但很明显> p + scale_fill_manual(values = c("red", "blue", "green", "purple", "pink"), labels = c("Cat1", "Cat2", "Cat3", "Cat4", "Cat5"), drop=FALSE)很重要且整个答案

      scale_x_discrete

    3. enter image description here

      ANSWER 以上示例礼貌@Bouncyball&amp; @aosmith

      scale_x_discrete

      enter image description here

1 个答案:

答案 0 :(得分:2)

以下是您可以使用的解决方法:

# generate dummy data 
set.seed(123)
df1 <- data.frame(lets = sample(letters[1:4], 20, replace = T),
                  y = rnorm(20), stringsAsFactors = FALSE)
# define factor, including the missing category as a level
df1$lets <- factor(df1$lets, levels = letters[1:5])
# make plot
ggplot(df1, aes(x = lets, y = y))+
    geom_boxplot(aes(fill = lets))+
    geom_point(data = NULL, aes(x = 'e', y = 0), pch = NA)+
    scale_fill_brewer(drop = F, palette = 'Set1')+
    theme_bw()

enter image description here

基本上,我们绘制一个&#34;空&#34;点(即pch = NA),以便类别显示在x轴上,但没有与之关联的可见geom。我们还将离散变量lets定义为factor,当data.frame中只有四个时,它们有五个级别。缺少的类别是字母e

NB :您必须调整此&#34;空白&#34;的定位。这样它就不会使你的y轴倾斜。

否则,您可以使用this answer的结果来避免必须绘制&#34;空&#34;点。

# generate dummy data 
set.seed(123)
df1 <- data.frame(lets = sample(letters[1:4], 20, replace = T),
                  y = rnorm(20), stringsAsFactors = FALSE)
# define factor, including the missing category as a level
df1$lets <- factor(df1$lets, levels = letters[1:5])
# make plot
ggplot(df1, aes(x = lets, y = y)) +
    geom_boxplot(aes(fill = lets)) +
    scale_x_discrete(drop = F) +
    scale_fill_brewer(drop = F, palette = 'Set1') +
    theme_bw()

enter image description here

相关问题