2014-07-24 2 views
0

10 개의 점포에 대한 판매 데이터가 있습니다. 상점 당 매출의 막대 그래프와 누적 판매의 라인 플롯을 보여주는 결합 된 플롯을 원합니다.ggplot2를 사용하여 결합 된 막대 그래프와 누적 line_plot을 그리는 방법

두 그래프를 별도로 플롯 할 수 있지만 두 그래프를 동일한 그래프에 재현하는 방법을 모르겠습니다. ggplot2를 처음 사용하기 때문에 여분의 포인터를 많이 사용하게 될 것입니다.

내 데이터 :

data <- structure(list(Stores = c("store1", "store2", "store3", "store4", 
"store5", "store6", "store7", "store8", "store9", "store10"), 
Sales = c(243.42, 180.02, 156.51, 145.09, 141.9, 104.9, 102.61, 
101.09, 88.53, 84.2), CumulativeSales = c(243.42, 423.44, 
579.95, 725.04, 866.94, 971.84, 1074.45, 1175.54, 1264.07, 
1348.27)), .Names = c("Stores", "Sales", "CumulativeSales" 
), row.names = c(NA, 10L), class = "data.frame") 

자체로 히스토그램을 플로팅 :

data_hist <- data[,1:2] 
p_hist <- (ggplot(data=data_hist, aes(x=Stores, y=Sales, fill=Stores)) + 
         geom_bar(fill="#DD8888", width=.7, stat="identity") + 
         guides(fill=FALSE) + 
         xlab("Stores") + ylab("Sales") + 
         theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + 
         scale_y_continuous(breaks=seq(0,2600,50))) + 
    scale_x_discrete(limits=data[,1]) 
p_hist 

그 자체로 선을 플로팅 :

data_line <- data[,c(1,3)] 
p_line <- (ggplot(data=data_line, aes(x=Stores, y=CumulativeSales, group=1)) + 
     geom_line(fill="#DD8888", size=1.5) + 
     geom_point(size=3, fill="white") + 
     xlab("Stores") + ylab("Sales") + 
     theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + 
     scale_y_continuous(breaks=seq(0,2600,50))) + 
scale_x_discrete(limits=data[,1]) 
p_line 

어떻게 하나의 그래프에 함께 음모 수 있습니까?

참고 : 원본 코드를 수정하면 환영 할만한 가치가 있습니다 (그래프를 개선하는 데 도움이되는 모든 것).

+0

http://stackoverflow.com/questions/21109567/plot-density-and-cumulative-density-function-in-one-combined-plot-using-ggplot2이 도움이 될한다 당신. 거기에 경험적 CDF가 사용되었습니다. –

답변

2

당신은 당신의 원본 데이터 프레임을 사용하고 geom_line()geom_point()에 대한 Y로 geom_bar()CumulativeSales에 대한 Sales 등의 y 값을 사용할 수 있습니다. group=1aes()geom_line()으로 추가하면 데이터가 연결됩니다. 범례가 필요한 경우 한 가지 방법은 표시하려는 이름으로 aes() 안에 fill=linetype=을 넣는 것입니다.

ggplot(data=data, aes(x=Stores)) + 
     geom_bar(aes(y=Sales,fill="Sales"), width=.7, stat="identity") + 
     geom_line(aes(y=CumulativeSales,group=1,linetype="Cumulative sales"))+ 
     geom_point(aes(y=CumulativeSales))+ 
     xlab("Stores") + ylab("Sales") + 
     labs(fill="",linetype="")+ 
     theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust=0.5)) + 
     scale_x_discrete(limits=data[,1]) 

enter image description here

+0

위대한, 고마워! CumulativeSales를 기반으로 geom_point()를 추가 할 수도 있습니까? – user3580643

+0

@ user3580643 내 대답이'geom_point()'로 업데이트되었습니다. –

+0

고마워요. 마지막 질문 하나. 어떻게 검은 선이 누적 판매이고 빨간색 막대가 매출인지를 나타내는 키 (범례)를 추가 할 수 있습니까? – user3580643

관련 문제