繁体   English   中英

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

[英]How to add a legend for two geom layers in one ggplot2 plot?

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

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

这会产生一个像这样的情节:

在此处输入图片说明

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

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

阴谋

示例数据集:

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

该解决方案旨在从 1 个数据框中绘制 2 条曲线。 一列数据绘制为针对 x 轴(观察日期)的折线图,另一列数据绘制为针对同一 x 轴(观察日期)的面积图 面积曲线将位于次要 y 轴上。 图例绘图和格式也显示在所附的图像中。 希望你喜欢这个解决方案。

数据框结构如下所示/这是整个数据集的示例,我将选择 2 列,obsdate、revenue 和 value:

这是整个数据集的样本,我将选择 2 列,obsdate、revenue 和 value

我正在使用 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) 

输出将是:

输出曲线

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM