문제

나는 어떻게 만드는 방법에 어려움을 겪고있다 파레토 차트 ggplot2 패키지를 사용하여 R에서. 막대 차트 나 히스토그램을 만들 때 많은 경우 x 축으로 항목을 정렬하기를 원합니다. 파레토 차트에서 우리는 y 축의 값에 따라 주문한 항목을 원합니다. y 축의 값으로 주문한 항목을 플롯 할 수있는 방법이 있습니까? 먼저 데이터 프레임을 정렬하려고 시도했지만 GGPlot이 다시 표시되는 것 같습니다.

예시:

val <- read.csv("http://www.cerebralmastication.com/wp-content/uploads/2009/11/val.txt")
val<-with(val, val[order(-Value), ])
p <- ggplot(val)
p + geom_bar(aes(State, Value, fill=variable), stat = "identity", position="dodge") + scale_fill_brewer(palette = "Set1")

데이터 프레임 VAL은 정렬되었지만 출력은 다음과 같습니다.

alt text
(원천: Cerebralmastication.com)

Hadley는 이것이 실제 대 예측을 보여주는 훨씬 더 나은 그래픽을 생성한다고 정확하게 지적했습니다.

ggplot(val, aes(State, Value)) + geom_bar(stat = "identity", subset = .(variable == "estimate"), fill = "grey70") + geom_crossbar(aes(ymin = Value, ymax = Value), subset = .(variable == "actual"))

반환 :

alt text
(원천: Cerebralmastication.com)

그러나 여전히 파레토 차트가 아닙니다. 팁이 있습니까?

도움이 되었습니까?

해결책

GGPLOT2의 막대는 요인의 레벨을 순서로 주문합니다.

val$State <- with(val, factor(val$State, levels=val[order(-Value), ]$State))

다른 팁

데이터 서브 세트 및 정렬;

valact <- subset(val, variable=='actual')
valsort <- valact[ order(-valact[,"Value"]),]

거기에서 그것은 단지 표준입니다 boxplot() 맨 위에 매우 수동 누적 기능이 있습니다.

op <- par(mar=c(3,3,3,3)) 
bp <- barplot(valsort [ , "Value"], ylab="", xlab="", ylim=c(0,1),    
              names.arg=as.character(valsort[,"State"]), main="How's that?") 
lines(bp, cumsum(valsort[,"Value"])/sum(valsort[,"Value"]), 
      ylim=c(0,1.05), col='red') 
axis(4)
box() 
par(op)

이렇게 보일 것입니다

alt text
(원천: eddelbuettel.com)

그리고 오버 플롯 트릭이 필요하지 않습니다 lines() 행복하게 초기 플롯에 주석을 달 수 있습니다.

GGPLOT2의 전통적인 파레토 차트 .......

Cano, El, Moguerza, JM, & Redchuk, A. (2012)를 읽은 후 개발되었습니다. R. (G. Robert, K. Hornik, & G. Parmigiani, eds.)와 Six Sigma.

library(ggplot2);library(grid)

counts  <- c(80, 27, 66, 94, 33)
defects <- c("price code", "schedule date", "supplier code", "contact num.", "part num.")
dat <- data.frame(count = counts, defect = defects, stringsAsFactors=FALSE )
dat <- dat[order(dat$count, decreasing=TRUE),]
dat$defect <- factor(dat$defect, levels=dat$defect)
dat$cum <- cumsum(dat$count)
count.sum<-sum(dat$count)
dat$cum_perc<-100*dat$cum/count.sum

p1<-ggplot(dat, aes(x=defect, y=cum_perc, group=1))
p1<-p1 + geom_point(aes(colour=defect), size=4) + geom_path()

p1<-p1+ ggtitle('Pareto Chart')+ theme(axis.ticks.x = element_blank(), axis.title.x = element_blank(),axis.text.x = element_blank())
p1<-p1+theme(legend.position="none")

p2<-ggplot(dat, aes(x=defect, y=count,colour=defect, fill=defect))
p2<- p2 + geom_bar()

p2<-p2+theme(legend.position="none")

plot.new()
grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))
print(p1, vp = viewport(layout.pos.row = 1,layout.pos.col = 1))
print(p2, vp = viewport(layout.pos.row = 2,layout.pos.col = 1))

간단한 예제 :

 > data
    PC1     PC2     PC3     PC4     PC5     PC6     PC7     PC8     PC9    PC10 
0.29056 0.23833 0.11003 0.05549 0.04678 0.03788 0.02770 0.02323 0.02211 0.01925 

barplot(data) 올바르게 일을합니다

GGPlot 동등한 "이어야합니다": qplot(x=names(data), y=data, geom='bar')

그러나 그것은 막대를 알파벳순으로 반대/정렬합니다. levels(factor(names(data))) 주문됩니다.

해결책: qplot(x=factor(names(data), levels=names(data)), y=data, geom='bar')

휴!

또한 패키지를 참조하십시오 QCC 기능이 있습니다 pareto.chart(). 기본 그래픽도 사용하는 것처럼 보이므로 ggplot2-solution을 위해 바운티를 시작하십시오 :-)

물건을 단순화하려면 추정치 만 고려해 봅시다.

estimates <- subset(val, variable == "estimate")

먼저 우리는 요인 레벨을 재정렬하여 StateS는 감소 순서로 표시됩니다 Value.

estimates$State <- with(estimates, reorder(State, -Value))

마찬가지로 데이터 세트를 재정렬하고 누적 값을 계산합니다.

estimates <- estimates[order(estimates$Value, decreasing = TRUE),]
estimates$cumulative <- cumsum(estimates$Value)

이제 우리는 줄거리를 그릴 준비가되었습니다. 동일한 축에서 선과 막대를 얻는 트릭은 상태 변수 (요인)를 숫자로 변환하는 것입니다.

p <- ggplot(estimates, aes(State, Value)) + 
  geom_bar() +
  geom_line(aes(as.numeric(State), cumulative))
p

이 질문에서 언급했듯이, 서로 바로 옆에있는 두 개의 가변 그룹의 두 파레토 플롯을 그리는 것은 쉽지 않습니다. 여러 파레토 플롯을 원한다면 패싯팅을 사용하는 것이 좋습니다.

freqplot = function(x, by = NULL, right = FALSE)
{
if(is.null(by)) stop('Valor de "by" precisa ser especificado.')
breaks = seq(min(x), max(x), by = by )
ecd = ecdf(x)
den = ecd(breaks)
table = table(cut(x, breaks = breaks, right = right))
table = table/sum(table)

intervs = factor(names(table), levels = names(table))
freq = as.numeric(table/sum(table))
acum = as.numeric(cumsum(table))

normalize.vec = function(x){
  (x - min(x))/(max(x) - min(x))
}

dados = data.frame(classe = intervs, freq = freq, acum = acum, acum_norm = normalize.vec(acum))
p = ggplot(dados) + 
  geom_bar(aes(classe, freq, fill = classe), stat = 'identity') +
  geom_point(aes(classe, acum_norm, group = '1'), shape = I(1), size = I(3), colour = 'gray20') +
  geom_line(aes(classe, acum_norm, group = '1'), colour = I('gray20'))

p
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top