【发布时间】:2015-09-12 11:40:00
【问题描述】:
我正在尝试更改数据框列的因子级别排序,以控制由国家名称指定的因子级别的图例排序和 ggplot 着色。这是我的数据框country_hours:
countries hours
1 Brazil 17
2 Mexico 13
3 Poland 20
4 Indonesia 2
5 Norway 20
6 Poland 20
这是我尝试根据所选国家/地区列表绘制数据框子集的方法,user_countries:
make_country_plot<-function(user_countries, country_hours_pre)
{
country_hours = country_hours_pre[which(country_hours_pre$countries %in% user_countries) ,]
country_hours$countries = factor(country_hours$countries, levels = c(user_countries))
p = ggplot(data=country_hours, aes(x=hours, color=countries))
for(name in user_countries){
p = p + geom_bar( data=subset(country_hours, countries==name), aes(y = (..count..)/sum(..count..), fill=countries), binwidth = 1, alpha = .3)
}
p = p + scale_y_continuous(labels = percent) + geom_density(size = 1, aes(color=countries), adjust=1) +
ggtitle("Baltic countries") + theme(plot.title = element_text(lineheight=.8, face="bold")) + scale_fill_discrete(breaks = user_countries)
}
这很有效,因为着色按照我想要的顺序进行,顶部图例也是如此,但是第二个图例出现并显示不同的顺序。没有scale_fill_discrete(breaks = user_countries) 我没有得到我想要的订单,但我也没有得到两个图例。在下图中,user_countries 给出的所需顺序是
user_countries = c("Lithuania", "Latvia", "Estonia")
我想摆脱第二个传说。我该怎么做?
我还有另一个问题,就是不同地块之间的绘图/着色不一致。我希望“第一个”国家永远是蓝色的,但它并不总是蓝色的。此外,“真实”图例(较深/纯色)并不总是位于同一位置 - 有时它位于不正确/黑色图例下方。 为什么会发生这种情况,我怎样才能使这种情况在不同的情节中保持一致?
另外,不同的地块有不同数量的因子组,有时超过 9 个,所以我宁愿坚持使用标准的 ggplot 着色,因为大多数定义自己颜色的解决方案似乎限制了你可以做的颜色数量( How to assign colors to categorical variables in ggplot2 that have stable mapping?)
【问题讨论】:
-
尝试将
+ theme(legend.position="none")添加到您希望在没有图例的情况下显示的绘图定义部分。如果没有可重复的数据,我无法确定它是否有效,但我相信值得一试。