Plot with 2 y axes

118 views
Skip to first unread message

Thang Khong

unread,
Aug 19, 2016, 7:12:53 AM8/19/16
to ggplot2
Dear all,
I want to draw a plot with two different y axes using ggplot2.

df <- read.csv(file.choose(), header =  TRUE)
summary(df)
head(df)

##-------------

library(ggplot2)
library(reshape2)
library(reshape)
library(doBy)
library(gmodels)
library(gtable)
library(grid)

#-------
grid.newpage()
#------- Vol Chart

df_wk_sum <- as.data.frame(table(df$WeekNum))
colnames(df_wk_sum) <- c('wk','amount')
df_wk_sum
c1 <- ggplot(df_wk_sum, aes(x = wk,y = amount)) + geom_bar(stat = 'identity', fill='steelblue') +
            geom_text(aes(label=amount), vjust = 1.6, color = 'white', size = 3.5)+
            ggtitle("Volume and Delivery LT")
            theme_minimal()
c1
###-------

df_avg_lt <- subset(df, select = c("WeekNum", "Delivery.Leadtime"))
df_avg_lt <- summaryBy(data = df_avg_lt,  df_avg_lt$Delivery.Leadtime  ~ df_avg_lt$WeekNum, FUN = mean, na.rm = TRUE)
df_avg_lt$WeekNum <- as.factor(df_avg_lt$WeekNum)
df_avg_lt
colnames(df_avg_lt) <- c('wk','lt')
df_avg_lt$lt <- round(df_avg_lt$lt, digits = 2)
c2 <- ggplot(df_avg_lt, aes(x = wk, y = lt,group=1)) + geom_line(color="orange") + geom_point()+
  geom_text(aes(label=lt), vjust = 1.3, color='black')

c2

#---------------
g1<-ggplot_gtable(ggplot_build(c1))
g2<-ggplot_gtable(ggplot_build(c2))

pp<-c(subset(g1$layout,name=="panel",se=t:r))
g<-gtable_add_grob(g1, g2$grobs[[which(g2$layout$name=="panel")]],pp$t,pp$l,pp$b,pp$l)

ia<-which(g2$layout$name=="axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

grid.draw(g)

#-----------------
 But it does't work, you can let me know the reasons for this issue, pls!

GHN Week 33.csv

Brandon Hurr

unread,
Aug 19, 2016, 4:43:57 PM8/19/16
to Thang Khong, ggplot2
Could you explain what you mean by "doesn't work"? 

Inline image 1

Seems like there are two axes on my screen. 

> devtools::session_info()
Session info -------------------------------------------------------------------------------------------------------------------------
 setting  value                       
 version  R version 3.3.0 (2016-05-03)
 system   x86_64, darwin13.4.0        
 ui       AQUA                        
 language (EN)                        
 collate  en_US.UTF-8                 
 tz       America/Los_Angeles         
 date     2016-08-19                  

Packages -----------------------------------------------------------------------------------------------------------------------------
 package    * version date       source                         
 assertthat   0.1     2013-12-06 CRAN (R 3.3.0)                 
 colorspace   1.2-6   2015-03-11 CRAN (R 3.3.0)                 
 DBI          0.4-1   2016-05-08 CRAN (R 3.3.0)                 
 devtools     1.11.1  2016-04-21 CRAN (R 3.3.0)                 
 digest       0.6.10  2016-08-02 CRAN (R 3.3.0)                 
 dplyr      * 0.5.0   2016-06-24 CRAN (R 3.3.0)                 
 ggplot2    * 2.1.0   2016-05-28 Github (hadley/ggplot2@b181e9a)
 gtable     * 0.2.0   2016-02-26 CRAN (R 3.3.0)                 
 labeling     0.3     2014-08-23 CRAN (R 3.3.0)                 
 lattice      0.20-33 2015-07-14 CRAN (R 3.3.0)                 
 lazyeval     0.2.0   2016-06-12 CRAN (R 3.3.0)                 
 magrittr     1.5     2014-11-22 CRAN (R 3.3.0)                 
 Matrix       1.2-6   2016-05-02 CRAN (R 3.3.0)                 
 memoise      1.0.0   2016-01-29 CRAN (R 3.3.0)                 
 mgcv         1.8-12  2016-03-03 CRAN (R 3.3.0)                 
 munsell      0.4.3   2016-02-13 CRAN (R 3.3.0)                 
 nlme         3.1-128 2016-05-10 CRAN (R 3.3.0)                 
 plyr         1.8.4   2016-06-08 CRAN (R 3.3.0)                 
 R6           2.1.2   2016-01-26 CRAN (R 3.3.0)                 
 Rcpp         0.12.6  2016-07-19 CRAN (R 3.3.0)                 
 reshape    * 0.8.5   2014-04-23 CRAN (R 3.3.0)                 
 reshape2   * 1.4.1   2014-12-06 CRAN (R 3.3.0)                 
 scales       0.4.0   2016-02-26 CRAN (R 3.3.0)                 
 stringi      1.1.1   2016-05-27 CRAN (R 3.3.0)                 
 stringr      1.0.0   2015-04-30 CRAN (R 3.3.0)                 
 tibble       1.1     2016-07-04 CRAN (R 3.3.0)                 
 withr        1.0.1   2016-02-04 CRAN (R 3.3.0) 

B

Thang Khong

unread,
Aug 22, 2016, 1:42:10 AM8/22/16
to ggplot2, khongth...@gmail.com

Here is my expected result.



Vào 03:43:57 UTC+7 Thứ Bảy, ngày 20 tháng 8 năm 2016, Brandon Hurr đã viết:

Brandon Hurr

unread,
Aug 22, 2016, 10:55:29 AM8/22/16
to Thang Khong, ggplot2
Thang, 

The problem with the appearance was due to my lack of doBY. I rewrote it for dplyr. 

df <- read.csv("~/Downloads/GHN Week 33.csv", header =  TRUE)
summary(df)
head(df)

##-------------

library(ggplot2)
library(dplyr)
library(gmodels)
library(gtable)
library(grid)

#-------
grid.newpage()
#------- Vol Chart

df_wk_sum <- as.data.frame(table(df$WeekNum))
colnames(df_wk_sum) <- c('wk','amount')
df_wk_sum

c1 <-
ggplot(df_wk_sum, aes(x = factor(wk), y = amount)) + 
geom_bar(stat = 'identity', fill='steelblue') +
    geom_text(aes(label=amount), vjust = 1.6, color = 'white', size = 3.5)+
    ggtitle("Volume and Delivery LT") +
    theme_minimal()
c1
###-------

df_avg_lt <- 
df %>%
select(WeekNum, Delivery.Leadtime) %>%
group_by(WeekNum) %>%
summarise(AvgDeliveryLeadtime = round(mean(Delivery.Leadtime, na.rm=TRUE), digits = 2)) %>%
mutate(WeekNum = factor(WeekNum)) %>%
rename(wk= WeekNum, lt = AvgDeliveryLeadtime)

df_avg_lt

c2 <- 
ggplot(df_avg_lt, aes(x = wk, y = lt, group=1)) + 
geom_line(color="orange") + 
geom_point()+
  geom_text(aes(label=lt), vjust = 1.3, color='black') +  
  theme_void()

c2

#---------------
g1<-ggplot_gtable(ggplot_build(c1))
g2<-ggplot_gtable(ggplot_build(c2))

pp<-c(subset(g1$layout,name=="panel",se=t:r))
g<-gtable_add_grob(g1, g2$grobs[[which(g2$layout$name=="panel")]],pp$t,pp$l,pp$b,pp$l)

ia<-which(g2$layout$name=="axis-l")
ga <- g2$grobs[[ia]]
ax <- ga$children[[2]]
ax$widths <- rev(ax$widths)
ax$grobs <- rev(ax$grobs)
ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1)
g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)

grid.draw(g)

There is still an error, but I don't know enough about grobs to know why:
> ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
Error in Ops.unit(ax$grobs[[1]]$x, unit(1, "npc")) : 
  both operands must be units

Inline image 1

HTH
B

--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+unsubscribe@googlegroups.com
More options: http://groups.google.com/group/ggplot2

---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages