如何在一个ggplot2图中为两个几何层添加图例?

11

我有一个数据框,长这样:

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()

这会生成一个如下所示的图:

在此输入图像描述

现在我想添加一些说明,说明线和列的含义。我该怎么做?谢谢!

2个回答

14

在 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()
在上面的示例中,我还将数据和公共美学映射(x)移动到ggplot()中。

plot

示例数据集:

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

它按照您描述的方式正常工作,非常感谢您详细的回答!唯一的问题是我不理解scale_*_manual()函数调用背后的逻辑,我该如何理解呢?无论如何还是感谢您!! :) - hpy
1
@hpy 很高兴能帮到你 :) scale_*_manual() 函数允许您以命名向量的形式指定自己的调色板,例如 c("a" = "red", "b" = "green"),其中 "a" 和 "b" 是相关变量中的值。在这种情况下,由于我不想填充/颜色因y.bar / y.line内的值而有所变化,因此就让每个变量在填充/颜色方面采用单一值。这有点不正规,但我发现它在实践中非常有效。 - Z.Lin
明白了,感谢您的解释!这对我非常有帮助。 - hpy

1
这个解决方案旨在绘制一个数据框中的两条曲线。一列数据将作为折线图绘制在x轴(观察日期)上,另一列数据将作为面积图绘制在同一x轴(观察日期)上,面积曲线将位于次要y轴上。附带的图片展示了图例绘制和格式设置。希望您喜欢这个解决方案。
数据框的结构如下所示/这是整个数据集的一个样本,我将选择两列,obsdate、revenue和value。

This is a sample of the whole dataset, I will pick 2 columns, obsdate, revenue, and value

我正在使用Shiny库将其托管到服务器上;如果你不了解Shiny,可以忽略,这只是布局~HTML。

library(xlsx) # Library for Excel import 
library (ggplot2) # Library for plot
library(openxlsx) #FOR Running the xlsx file 
library(shiny) #SERVER UI LIBRARY IN R
library(lubridate) # For converting the imported dates to Date Format

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接