【问题标题】:Defining Legends using ggplot使用 ggplot 定义图例
【发布时间】:2020-09-10 03:09:53
【问题描述】:

我正在尝试在 R 中定义我的情节图例。

我有以下代码,这只是一个演示,真实数据将有 7-8 列和最多 20 个样本

library(ggplot2)
library(RColorBrewer)


colors <-brewer.pal(n = 3, name = 'Paired')

ids <- c("TestA", "TestB", "TestC")
bg <-c(23, 13, 15)
sample1 <- c(21,15,17)
sample2 <- c(27,25,11)
sample3 <- c(24,14,18)
df <- data.frame(ids, bg, sample1,sample2,sample3)

ggplot(df) + 
  geom_col(aes(x = ids, y = bg), size = 1, color = "grey", fill = "grey") +
  geom_point(aes(x = ids, y = sample1), size = 10, color=colors[1], group = 1) +
  geom_point(aes(x = ids, y = sample2), size = 10, color=colors[2], group = 1) +
  geom_point(aes(x = ids, y = sample3), size = 10, color=colors[3], group = 1)+ 
  ggtitle("Plot title") +
  xlab("x label") + ylab(" y label") +
  scale_colour_manual(values = c("95% PI"= "black",
                                  "Forecasts"  = "red",
                                  "Threshold" = "green"))

它产生以下输出

如何添加如下图的图例,并确保颜色匹配,即图例颜色匹配样本或背景颜色

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是你想要的吗?

    ggplot(df) + 
      geom_col(aes(x = ids, y = bg, fill = "background"), size = 1, color = "grey") +
      geom_point(data = df %>% pivot_longer(cols = starts_with("sample"), names_to = "sample", values_to = "values"), aes(x = ids, y = values, color = sample), size = 10) +
      ggtitle("Plot title") +
      xlab("x label") + ylab(" y label") +
       scale_colour_manual(name = NULL, values = c("sample1"= "black",
                                     "sample2"  = "red",
                                     "sample3" = "green"),
                          labels = c("95% PI", "forecasts", "Threshold")) +
    scale_fill_manual(name = NULL, values = c("background" = "grey"))  
    

    【讨论】:

    • 嗨,Ben,示例名称会有所不同,它们可能是 x135、y923、ssamp3 等。生成 R 代码由基于所选输入的单独应用程序处理,图形通过对每个系列进行分层生成很好,唯一的问题是生成键/图例并将其放在图表的底部。
    • 添加+ theme(legend.position="bottom")
    猜你喜欢
    • 2018-09-15
    • 2014-08-26
    • 1970-01-01
    • 2022-01-09
    • 2022-01-23
    • 1970-01-01
    • 2021-08-14
    • 2020-07-28
    • 1970-01-01
    相关资源
    最近更新 更多