如何在一个ggplot2图中添加两个geom图层的图例?

时间:2017-10-30 20:38:17

标签: r plot ggplot2 legend legend-properties

我有一个如下所示的数据框:

glimpse(spottingIntensityByMonth)
# Observations: 27
# Variables: 3
# $ yearMonth <dttm> 2015-05-01, 2015-06-01, 2015-07-01, 2015-08-01, 2015-09-01, 2015-10-01, 2...
# $ nClassificationsPerDayPerSpotter <dbl> 3.322581, 13.212500, 13.621701,
    6.194700, 18.127778, 12.539589, 8.659722, ...
# $ nSpotters <int> 8, 8, 22, 28, 24, 22, 24, 27, 25, 29, 32, 32, 21, 14, 18, 13, 20, 19, 15, ...

我试图用ggplot2绘制它,如下所示:

ggplot() + 
    geom_col(data = spottingIntensityByMonth, 
             mapping = aes(x = yearMonth, 
                           y = nClassificationsPerDayPerSpotter)
             ) + 
    xlab("Month of year") + 
    scale_y_continuous(name = "Daily classifications per Spotter") + 
    geom_line(data = spottingIntensityByMonth, 
              mapping = aes(x = yearMonth,
                            y = nSpotters)
              ) +
    theme_bw()

这会产生如下情节:

enter image description here

现在我想添加一个说明行和列含义的图例。我该怎么做呢?谢谢!

2 个答案:

答案 0 :(得分:4)

在ggplot中,会自动为映射美学创建图例。您可以按如下方式添加此类映射:

ggplot(data = df, 
       mapping = aes(x = x)) + 

  # specify fill for bar / color for line inside aes(); you can use
  # whatever label you wish to appear in the legend
  geom_col(aes(y = y.bar, fill = "bar.label")) +
  geom_line(aes(y = y.line, color = "line.label")) +

  xlab("Month of year") + 
  scale_y_continuous(name = "Daily classifications per Spotter") + 

  # the labels must match what you specified above
  scale_fill_manual(name = "", values = c("bar.label" = "grey")) +
  scale_color_manual(name = "", values = c("line.label" = "black")) +

  theme_bw()

在上面的例子中,我还移动了数据&amp;共同美学映射(x)到ggplot()

plot

示例数据集:

set.seed(7)
df <- data.frame(
  x = 1:20,
  y.bar = rpois(20, lambda = 5),
  y.line = rpois(20, lambda = 10)
)

答案 1 :(得分:1)

  

此解决方案旨在从1个数据帧绘制2条曲线。一   列数据相对于x轴以折线图的形式绘制   (观察日期),另一个则相对于 Area Graph   相同的x轴(观测日期)。面积曲线位于第二   y轴。图例和格式设置也显示在   附加图片。希望您喜欢该解决方案。

     

数据帧结构如下所示:This is a sample of the whole dataset, I will pick 2 columns, obsdate, revenue, and value

     

我正在使用Shiny库将其托管在服务器上;如果你不知道   关于光泽,您可能会忽略,这只是布局〜HTML。

library(xlsx)#用于Excel导入的库     library(ggplot2)#绘图库     library(openxlsx)#FOR运行xlsx文件     library(shiny)#R中的SERVER UI库     library(lubridate)#用于将​​导入的日期转换为日期格式

file <- "C:/Users/Nikhil Asati/Desktop/Office/Bicurve_data.xlsx"
data1<- read.xlsx( file ,1)
data1$obsdate <- dmy(data1$obsdate)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(),
    mainPanel(
      plotOutput("Plot")
    )
  )
)
server <- function(input, output) {
  output$Plot <- renderPlot({
    #plot value
    p <- ggplot(data1, aes(x=obsdate))
        p <- p + geom_line(aes(y=revenue, colour ="revenue"))
    #plot revenue
        p <- p + geom_ribbon(aes(ymin = 0, ymax=value/16, fill = 'value'),  
                             linetype=1,     
                             #solid, dashed or other line types
                             colour="grey70",
                             #border line color
                             size=1
                             # ,show.legend= TRUE
        )
         p <- p + scale_y_continuous(sec.axis = sec_axis(~.*16, name = "value"))

         p<- p + scale_colour_manual("", values=c("revenue" = "Grey" ))
         p<- p +scale_fill_manual(name = "", values = c("value" = "green"))
         p<- p +theme(legend.position = "top") 
         p
  })

}


shinyApp(ui = ui, server = server) 
  

输出将为

Output Curve