ggplot:重复级别的因素顺序 [英] ggplot: order of factors with duplicate levels
本文介绍了ggplot:重复级别的因素顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
reorder()
,但我无法保存变量的原始顺序。 $ b $ ('Sp1','Su1','Au1','Wi1','Sp2','b1 b $ b pre $ require(ggplot2)
season < ,'Su2','Au2','Wi2','Sp3','Su3','Au3','Wi3')#这是我希望季节以
tempa < - rnorm (12,15)
tempb < - rnorm(12,20)
df < - data.frame(season = rep(season 2),temp = c(tempa, tempb),type = c(rep('A',12),rep('B',12)))
#X轴顺序错误:
ggplot (df,aes(x = season,y = temp,color = type,group = type))+ geom_point()+ geom_line()
#X轴顺序正确,但警告重复级别(df,aes(x =季节2,y =温度,颜色=类型,组=类型)的因子
df $ season2 < - 因子(df $ season,levels = df $ season)
ggplot )+ geom_point()+ geom_line()
解决方案
Ju因此这有一个答案,这工作得很好:
df $ season2 < - factor(df $ season,levels =独特(df $ season))
ggplot(df,aes(x = season2,y = temp,color = type,group = type))+
geom_point()+
geom_line()
ggplot changes the order of an axis variable, which I do not want. I know I can change the variable to a factor and specify the levels to get around this, but what if the levels contain duplicate values?
An example is below. The only alternative I can think of is to use reorder()
, but I can't get that to preserve the original order of the variable.
require(ggplot2)
season <- c('Sp1', 'Su1', 'Au1', 'Wi1', 'Sp2', 'Su2', 'Au2', 'Wi2', 'Sp3', 'Su3', 'Au3', 'Wi3') # this is the order I want the seasons to appear in
tempa <- rnorm(12, 15)
tempb <- rnorm(12, 20)
df <- data.frame(season=rep(season, 2), temp=c(tempa, tempb), type=c(rep('A',12), rep('B',12)))
# X-axis order wrong:
ggplot(df, aes(x=season, y=temp, colour=type, group=type)) + geom_point() + geom_line()
# X-axis order correct, but warning of duplicate levels in factor
df$season2 <- factor(df$season, levels=df$season)
ggplot(df, aes(x=season2, y=temp, colour=type, group=type)) + geom_point() + geom_line()
解决方案
Just so this has an answer, this works just fine:
df$season2 <- factor(df$season, levels=unique(df$season))
ggplot(df, aes(x=season2, y=temp, colour=type, group=type)) +
geom_point() +
geom_line()
这篇关于ggplot:重复级别的因素顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文