1

Datalink:

Data

Code:

    distevyield <- read.csv(file = "F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/GTAP-CGE/GTAP_NewAggDatabase/NewFiles/GTAP_DistEVYield.csv", header=TRUE, sep=",", na.string="NA", dec=".", strip.white=TRUE)

    str(distevyield)
    distevyield <- as.data.frame(distevyield)
    distevyield[5:6] <- sapply(distevyield[5:6],as.numeric)
    distevyield <- droplevels(distevyield)
    distevyield <- transform(distevyield,region=factor(region,levels=unique(region)))
    library(ggplot2)

    distevyield.f <- melt(subset(distevyield, region !="World"))

    Figure3 <- ggplot(data = distevyield.f, aes(factor(variable), value)) 
    Figure3 + geom_boxplot() +
    theme(axis.text.x = element_text(colour = 'black', angle = 90, size = 15, hjust = 1, vjust = 0.5),axis.title.x = element_blank()) + 
    theme(axis.text.y = element_text(colour = 'black', size = 15, hjust = 0.5, vjust = 0.5), axis.title.y = element_blank()) + 
    theme(strip.text.x = element_text(size = 14, hjust = 0.5, vjust = 0.5, face = 'bold')) +
    facet_wrap(~region, scales="free_y")

Outcome: Plot result

Question:

My two variables plotted, yield (%change) and ev (in million US$) have different units. Is there a way to add a secondary y-axis for one of the variable so as to display each variable with a boxplot representing its original units, but within the same plot? Does this feature exist in ggplot2 to begin with?

Thanks!

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
iouraich
  • 2,944
  • 5
  • 29
  • 40

1 Answers1

6

With ggplot2 you can't make two y axis (see explanation/discussion).

To represent different axis values for ev and yield you have to plot them in separate plots. One way to achieve this would be to use facet_wrap() and combine region and variable values. With facet_wrap() you will get both plots together and you will be able to control number of columns to show.

ggplot(data = distevyield.f, aes(factor(1), value)) +
  geom_boxplot() +  facet_wrap(region~variable,scales="free",ncol=8)+
  theme(axis.text.x=element_blank(),
        axis.title.x=element_blank(), 
        axis.title.y = element_blank())

enter image description here

Community
  • 1
  • 1
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201