I have data that are in several groups, and I want to display them in a faceted stacked bar chart. The data show responses to a survey question. When I look at them in the dataframe, they make sense, and when I plot them (without faceting), they make sense.
However the data appear to change when they are faceted. I have never had this problem before. I was able to re-create a change (not the exact same change) with some dummy data.
myDF <- data.frame(rep(c('aa','ab','ac'), each = 9),
rep(c('x','y','z'),times = 9),
rep(c("yes", "no", "maybe"), each=3, times=3),
sample(50:200, 27, replace=FALSE))
colnames(myDF) <- c('place','program','response','number')
library(dplyr)
myDF2 <- myDF %>%
group_by(place,program) %>%
mutate(pct=(100*number)/sum(number))
The data in myDF
are basically a count of responses to a question. The myDF2
only creates a percent of respondents with any particular response within each place and program.
library(ggplot2)
my.plot <-ggplot(myDF2,
aes(x=place, y=pct)) +
geom_bar(aes(fill=myDF$response),stat="identity")
my.plot.facet <-ggplot(myDF2,
aes(x=place, y=pct)) +
geom_bar(aes(fill=myDF$response),stat="identity")+
facet_wrap(~program)
각 "프로그램"과 "장소"내에서 각 "응답"에 대한 적절한 "pct"를 보여주는 플롯을보고 싶습니다. 그러나 my.plot.facet
장소 당 하나의 "응답"만 표시합니다.
데이터는 그렇지 않습니다. 예를 들어 head(myDF2)
는 'x'위치의 프로그램 'aa'에 yes와 no가 모두 있음을 보여줍니다.
> head(myDF2)
Source: local data frame [6 x 5]
Groups: place, program
place program response number pct
1 aa x yes 69 18.35106
2 aa y yes 95 25.81522
3 aa z yes 192 41.64859
4 aa x no 129 34.30851
5 aa y no 188 51.08696
6 aa z no 162 35.14100
여기서 주문이 중요하다는 것이 밝혀졌습니다. myDF2는 더 이상 데이터 프레임이 아닙니다. dplyr 객체입니다. 이는 ggplot2가 실제로 어려움을 겪고 있음을 의미합니다.
데이터가 프로그램에 의해 패싯되어야하는 경우 '프로그램'을 먼저 호출해야합니다. group_by()
역 플롯 패싯을 살펴보면 이것이 사실입니다.
my.plot.facet2 <-ggplot(myDF2,
aes(x=program, y=pct)) +
geom_bar(aes(fill=myDF2$response),stat="identity")+
facet_wrap(~place)
생성 :
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다