ggplot2 0.9.0 自动从图例中删除未使用的因子水平? [英] ggplot2 0.9.0 automatically dropping unused factor levels from plot legend?

查看:22
本文介绍了ggplot2 0.9.0 自动从图例中删除未使用的因子水平?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近从 0.8.9 版本升级到 ggplot2 0.9.0,现在我发现我的情节图例仅显示情节中使用的因子级别(它省略了未使用的因子级别).在它包括图例中的所有因子水平之前.我运行的是 Windows 7 和 R 2.15.0(今天之前是 2.14.2).

I recently upgraded to ggplot2 0.9.0 from version 0.8.9, and now I'm getting that my plot legends only show the factor levels used in the plot (it omits the unused ones). Before it'd include all factor levels in the legend. I'm running Windows 7 and R 2.15.0 (2.14.2 before today).

还有人发现这个吗?有没有办法让未使用的因子水平显示在我的图例中?

Is anyone else finding this too? Is there a way I can get the unused factor levels to display in my plot legend?

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() 曾经给我两个苹果"和橙色"在图例中(即使苹果"只有点数).现在我只得到苹果"在传说中.

The qplot() used to give me both "apple" and "orange" in the legend (even though there were only points for "apple"). Now I only get "apple" in the legend.

出现这种情况的原因 - 我正在制作数据集子集的许多图,并且我希望图例之间标准化(通常我希望自动删除未使用的级别并且不必键入 droplevels(),但是这是我想要那些未使用的级别的一种情况).如果这只是我的计算机本地的问题,我深表歉意.

Reason this came up - I am making many plots of subsets of a data set and I want the legends standardized across plots (normally I'd appreciate the unused levels being automatically dropped and not having to type droplevels(), but this is the one case I want those unused levels). Apologies if this is a question local to my computer only.

编辑:请注意,从 R 4.0.0 开始,上述代码不再生成 df$fruit 作为因子,这会改变 的行为ggplot 在下面的问题和答案中.重现使用:

Edit: Note that as of R 4.0.0, the above code no longer produces a df$fruit as a factor, which changes the behavior of ggplot in the question and answers below. To reproduce use:

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

推荐答案

是的,您想将 drop = FALSE 添加到您的色标中:

Yes, you want to add drop = FALSE to your colour scale:

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

这篇关于ggplot2 0.9.0 自动从图例中删除未使用的因子水平?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆