如何编辑R中多线ggplot图的图例?

时间:2015-08-05 20:06:12

标签: r plot ggplot2 legend

我正在将两个带有自变量的数据系列绘制到一个图表上。虽然情节看起来很棒,但我无法控制传说。 文件(原始数据和图表)为here

代码如下:

ggplot()+  
geom_line(data = data_fluka,
          aes(x = depth_fluka, y = dose_fluka_norm, color = "blue"), size=1.01)+  
geom_line(data = data_geant,
          aes(x = depth_geant, y = dose_geant_norm, color = "red"), size=1.01)+  
    labs(size= "1", x = "Depth (mm)", y = "Normalised Dose",
         title = 'Dose Depth Comparison', vjust=-10)+  
    theme(axis.text=element_text(size=16),
        axis.text.x = element_text(angle=0, vjust=1),
        axis.title=element_text(size=16), 
        legend.position="top")+  
    theme(plot.title = element_text(size = 18))+
    ylim(c(0,1)) + xlim(c(0,25))+  
    scale_fill_discrete(name=" ", labels=c("GEANT4", "FLUKA")) 

我能得到的是上面的链接文件夹。

1 个答案:

答案 0 :(得分:1)

我建议将您的数据合并到一个数据框中,并按“类型”(Fluka vs Geant4)进行分层,以便更好地控制图例:

names(data_fluka) <- c("Depth", "NormalizedDose")
data_fluka$type  <- "FLUKA"

names(data_geant) <- c("Depth", "NormalizedDose")
data_geant$type  <- "GEANT4"

dat <- rbind(data_fluka, data_geant)

ggplot(dat, aes(x = Depth, y = NormalizedDose))+  
     geom_line(size=1.01, aes(colour = type))+  
     labs(size= "1", x = "Depth (mm)", y = "Normalised Dose",
          title = 'Dose Depth Comparison', vjust=-10)+  
     theme(axis.text=element_text(size=16),
           axis.text.x = element_text(angle=0, vjust=1),
           axis.title=element_text(size=16), 
           legend.position="bottom", legend.direction = "vertical", #change location and direction of legend
           legend.text = element_text(colour="blue", size = 16, face = "bold"))+  #change style for legend text
     theme(plot.title = element_text(size = 18))+
     ylim(c(0,1)) + xlim(c(0,25))