ggplot2를 사용하여 누적 막대 그림을 플로팅하고 싶은데 색상 매핑과 스택 순서를 올바르게 가져 오는 데 어려움이 있습니다. 다음 예제는 이 SO 답변 에서 0이 아닌 y 축 원점을 얻기 위해 개발 되었지만 보시다시피 다른 문제가 발생합니다. 색상이 제대로 매핑되지 않고 플롯 순서가 잘못되었습니다. 이를 처리하는 가장 좋은 방법에 대한 조언에 감사드립니다. 원하는 출력은에 대한 요인 수준에 rating
따라 지정된 순서대로 색상을 조정하여 색상을 조정해야합니다.
require(ggplot2)
d = data.frame(grp = rep(c('A','B'), each = 4),
rating = rep(c('bad','poor','ok','good'), 2),
value = c(15,45,35,5,5,15,55,30), stringsAsFactors = F)
if(require(reshape2)) reshape2::dcast(d, grp ~ rating) # show structure
d$rating = ordered(d$rating, levels=c('bad','poor','ok','good'))
d$grp = ordered(d$grp, levels=c('B','A'))
# split datsets so we can plot 'negative' bars
d1 = subset(d, rating %in% c('ok','good'))
d2 = subset(d, rating %in% c('poor','bad'))
ggplot() +
geom_bar(data = d1, aes(x=grp, y=value, fill=rating), stat='identity', position='stack') +
geom_bar(data = d2, aes(x=grp, y=-value, fill=rating), stat='identity', position='stack') +
scale_fill_manual(values=c('red','pink','lightgreen','green')) +
geom_line(data=d1, aes(x=c(.5,2.5), y=c(0,0)), size=2, linetype='dashed') +
coord_flip()
약간의 재정렬과 limits () 사용이 도움이 될 것입니다.
d2 <- d2[order(d2$rating, decreasing =T),]
ggplot() +
geom_bar(data = d1, aes(x=grp, y=value, fill=rating), stat='identity',
position='stack') +
geom_bar(data = d2, aes(x=grp, y=-value, fill=rating), stat='identity',
position='stack') +
scale_fill_manual(values=c('red','pink','lightgreen','green'),
limits=c("bad","poor","ok","good"))+
geom_line(data=d1, aes(x=c(.5,2.5), y=c(0,0)), size=2, linetype='dashed') +
coord_flip()
ggplot2를 배우고 자하는 사람이라면 Winston Chang의 R Graphics Cookbook을 구하는 것이 좋습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다