簡體   English   中英

R中的同一圖上繪制了2個具有相同x軸和facet_wrap的數據框

[英]2 dataframes with same x-axes and facet_wrap plotted on the same graph in R

該文件顯示了我到目前為止編寫的代碼。 我有以下兩個數據框,我想繪制Var1和Var2,它們在同一圖上具有相同的x軸但不同的y軸,並將它們分成四個季度。

目前,我正在使用以下代碼,但作為輸出,它提供了8個圖形而不是4個圖形。

創建我的兩個數據框,它們具有說的工作日和相同的季度,但是用於度量每個數據的比例在圖表上應不同

weekday <- c(1,2,3,4,5,6,7)
quarter <- c("15Q1", "15Q2", "15Q3", "15Q4")
Var1 <- c(0.03, 0.5, 0.9, 2.3, 6, 3.4, 3.89, 0.08, 0.9, 1.2, 2.8, 8, 3.9, 5, 0.8, 2.7, 0.1, 7, 2, 3, 10, 2, 3, 1.9, 3.3, 4, 5.4, 6.89 )
dataframe1 = data.frame(weekday, quarter, Var1)

Var2 <- c(1000, 10001, 1500, 3000,2000, 3642, 2687, 2008, 5209, 4589, 3642,5336, 5342, 8962, 2301, 1365, 2300, 7412,3642, 3548,2355, 5698, 6538, 9856, 3142, 5962, 1253, 2100 )
dataframe2 = data.frame(weekday, quarter, Var2)

## I am plotting the first data frame here
## I assign the graph to a variable so it is easier to plot them. Its a bar chart            

g <-ggplot(dataframe1, aes(x = dataframe1$weekday, y = dataframe1$Var1)) + 
            geom_bar(stat="identity", position=position_dodge()) + 
            facet_wrap(~quarter) + ##I am trying to separate them here
            labs(x = "Purchase Order Day", y = "Cycle Time", title = "Cycle Time Weekly Seasonality") ##I just rename the axes here

##I am plotting the second data frame here
##The second graph I am plotting should be a line

z <- ggplot(dataframe2, aes(x = dataframe2$weekday, y = dataframe2$Var2)) +
            geom_line() + 
            facet_wrap(~quarter) +
            labs(x = "Purchase Order Day", y = "Number of Orders per Day", title = "Number of Purchase Orders per Week")

##I am trying to bind the two graphs in here

grid.newpage()
grid.draw(bind(ggplotGrob(g), ggplotGrob(z), size = "last"))

這是組合兩種繪圖格式的解決方案。 但是對於您的數據,問題在於,線圖的y值比條形圖高得多,因此您看不到它們。 我對數據進行了歸一化,您可以決定如何處理它:

ggplot(dataframe1, aes(x = weekday, y = Var1)) + 
  geom_bar(stat="identity", position=position_dodge()) + 
  labs(x = "Purchase Order Day", y = "Cycle Time", title = "Cycle Time Weekly Seasonality")  +
  facet_wrap(~quarter) + 
  geom_line(data = dataframe2, aes(x = weekday, y = Var2/max(Var2)))

順便說一句:您當然可以將兩個數據幀組合為一個。

結果如下:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM