ggplot2秒y轴,调整高度

时间:2015-07-17 13:56:56

标签: r

我用ggplot2制作了一个带有第二个y轴的图,如下例所示:http://steffi.ca/thinkR/?p=91

一切正常。问题是第二个Y轴太高,以至于值不完全匹配。看到这张图片

Plot with too tall second y axis

第二个Y轴的y数据的最大值肯定是

enter image description here

在此图中,最大值为~19.7

当然我可以使用一个数据集调整所有内容(使用scale_y_continious),但我每天都会管理新的数据集,这些数据集都有不同的值等等...

我制作了可重现的代码:

library(reshape)                    # package for melting data
library(ggplot2)                    # package for beautiful plots
library(extrafont)              # package for nice fonts
library(grid)                   # package for smooth grid
library(RColorBrewer)               # package for beautiful color palettes
library('pracma')                   # linspace function

### Function for more and pretty axis-breaks ###

number_ticks <- function(n) {function(limits) pretty(limits, n)} 

### Prepare some Data ###

real_xdata <- seq(from=1,to=60,by=2)
real_ydata <- runif(30,0,40)

### Get Limits of Data ###

mmval <- matrix(1,
                nrow = 2,
                ncol = length(real_ydata)) 
                mmval <- range(as.numeric(real_ydata))
                xylim <- range(as.numeric(mmval))

### Prepare some Data for second y axis ###

real_ydata_two <- runif(30,0,378)

### Create Dataframe for ggplot2 ###

ggplot_data <- data.frame(matrix(NA,nrow=length(real_xdata),ncol=2))
ggplot_data$X1 <- real_xdata
ggplot_data$X2 <- real_ydata

### Transform Data from second Y-axis that it fits in first plot ###

dataset_second_yaxis <- real_ydata_two

sum1 <- summary(dataset_second_yaxis)

dataset_second_yaxis_two <-dataset_second_yaxis*((max(xylim)-min(xylim))/sum1[[6]])+ (min(xylim)-min(dataset_second_yaxis, na.rm=TRUE))

### Add transformed Data into Dataframe ###

i=ncol(ggplot_data)

ggplot_data[i+1]<-dataset_second_yaxis_two

### some color ###

colp <- c( brewer.pal(ncol(ggplot_data),"Spectral")[-2])


ggplot_one <- melt(ggplot_data, id = "X1") ### Melt Data ###
ggplot_one <- ggplot(data = ggplot_one, aes(x = X1, y = value, color =variable)) +
  geom_point() +  
  theme_gray() +
  scale_color_manual(                       #Legend
                     labels           = c("ydata_one","ydata_two"),
                     values           = colp) +
  scale_y_continuous(expand = c(0,0), limits = c(round(xylim[1]-0.04*xylim[2],digits=2), round(xylim[2]+0.04*xylim[2], digits=2)), breaks = number_ticks(10)) +  
  labs(x = "xaxis", y = "yaxis") +
  theme_gray() +
  theme(axis.text.x   = element_text(colour = "grey50", size = 10, vjust = 0.5, family = "Book Antiqua"),
        legend.title      = element_blank(),
        legend.text       = element_text(colour="grey50", size = 11, family = "Book Antiqua"),
        legend.position   = "top",
        legend.key        = element_rect(colour = 'white', fill = 'white'),
        panel.background  = element_rect(fill = "grey95"),
        panel.grid.minor  = element_line(colour = "grey98", size = 0.25), 
        panel.grid.major  = element_line(colour = "grey99", size = 0.25), 
        axis.text.y       = element_text(colour = "grey50", size = 10, family = "Book Antiqua"),
        axis.line     = element_line(colour = "grey50", size=0.25),
        axis.ticks    = element_line(size=0.25),
        axis.title.x      = element_text(colour = "black", size = 14, vjust=-0.5, family= "Book Antiqua"),
        axis.title.y      = element_text(colour = "black", size = 14, vjust= 2,  family= "Book Antiqua"),
        plot.margin = unit(c(2,0,1,1),units="lines"))+
      guides(colour = guide_legend(override.aes = list( size=3, linetype=0)))  ###Bigger points in legend

    ### Extract data from Plot for second Y-Axis ###

    build = ggplot_build(ggplot_one)
    breaks_gy <- build$panel$ranges[[1]]$y.labels
    breaks_gy <- as.numeric(breaks_gy)                      ### The points where I add the labels
    labels_gy <- linspace(min(xylim),max(xylim),length(breaks_gy))    ### linspace gives me the labels
    labels_gy <- round(labels_gy,digits=1)

    ### Second Y Axis ###

    gplot.y <- ggplot(ggplot_data, aes(x = X1, y = dataset_second_yaxis_two)) +
      geom_line(colour = "transparent") +
      theme_classic()+
      scale_y_continuous(breaks = breaks_gy, labels = labels_gy, expand = c(0,0),
                         limits = c(round(xylim[1]-0.04*xylim[2],digits=2), round(xylim[2]+0.04*xylim[2], digits=2))) +
      labs(y = "yaxis2") +
      theme(axis.title.y = element_text( vjust=-8, hjust =0.5, family= "Book Antiqua",size = 14, color=colp[length(colp)]),  
            axis.text.y = element_text(hjust=1.7, family= "Book Antiqua",colour =colp[length(colp)]),  
                            ## Reverse the ticks to go on the other side
            axis.ticks.length = unit(-0.15,"cm"),
                            ## Reverse spacing between ticks and text to move text to the right
            axis.ticks.margin = unit(-0.5, "cm"), 
            axis.title.x = element_blank(), ## Remove all x-axis attributes
            axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            axis.line.x = element_blank(),
            plot.background = element_rect(fill = "transparent"),
            plot.margin = unit(c(2,0,3.85,-2),units="lines"))


        vp1 <- viewport(width = 0.9, height = 1, x = 0, y = 0.5, just = c(0,0.5))
        vp2 <- viewport(width = 0.1, height = 1, x = 0.9, y = 0.5,just = c(0,0.5))

        print(ggplot_one,vp=vp1)
        print(gplot.y ,vp=vp2)

我整天都在寻找解决方案...... 希望有人可以提供帮助

0 个答案:

没有答案