2012-04-03 57 views
28

我最近从版本0.8.9升级到ggplot2 0.9.0,现在我知道我的情节图例只显示了情节中使用的因素级别(它省略了未使用的)。在它之前将所有因素级别包含在图例中。我正在运行Windows 7和R 2.15.0(今天之前的2.14.2)。ggplot2 0.9.0自动从绘图图例中删除未使用的因子水平?

其他人也发现了吗?有没有一种方法可以让我的情节图例中显示未使用的因子水平?

library(ggplot2) 

df <- data.frame(fruit = rep(c("apple", "orange"), times=11), 
       year = 1990:2011, 
       qty = rnorm(22, 100, 20)) 

# This plot only gives "apple" in the legend now. 
# Before, I used to get both "apple" and "orange". 
qplot(year, qty, data = subset(df, fruit=="apple"), colour = fruit) 

的qplot()用来给我两个“苹果”和“橘子”的传说(即使只为“苹果”点)。现在我只在传说中获得“苹果”。

这个问题出现了 - 我制作了许多数据集的子集,我想让图例在各个地块之间标准化(通常我会欣赏未使用的级别会自动下降而不必键入droplevels(),但这是我想要那些未使用的关卡的一种情况)。道歉,如果这只是我的电脑本地的问题。

回答

32

是的,您要添加drop = FALSE到您的色标:

ggplot(subset(df,fruit == "apple"),aes(x = year,y = qty,colour = fruit)) + 
    geom_point() + 
    scale_colour_discrete(drop = FALSE) 
1

的第二种方式是通过使用limits参数明确定义所需的条目:

ggplot(subset(df,fruit == "apple"),aes(x = year,y = qty,colour = fruit)) + 
    geom_point() + 
    scale_colour_discrete(limits = c("apple", "orange")) 
+1

由于种种原因,这个为scale_color_manual()工作,drop = FALSE没有 – zer0hedge 2017-09-04 10:51:29