r - 如何合并ggplot中的图例

标签 r ggplot2

我在合并图例时遇到问题,当前结果已分别指定线型、大小、形状和颜色。

我的数据如下所示:

library(ggplot2)
library(dplyr)
library(reshape2)
library(patchwork)
library(hrbrthemes)

rate="rate"
Jul="0.5‰"
Aug="0.6‰"
Sep="0.7‰"

df <- data.frame(rate,Jul,Aug,Sep)
df
d=melt(df,measure.vars = names(df)[2:4])
d
d$month=as.factor(d$variable)
d$percent=as.numeric(gsub("‰","",d$value))

我使用 ggplot2 绘制数据:

ggplot(d,aes(x=month,y=percent)) + 
  geom_point(aes(x=month,y=percent,color="Rate",shape="Rate"), size=2) +
  geom_text(aes(label = paste(format(percent, digits = 4, format = "f"), "‰")), 
            color="black",vjust = -0.5, size = 3.5) +
  geom_line(aes(x = month, y = percent, group=1, color="Rate",linetype = "Rate",size="Rate")) + 
  geom_hline(aes(yintercept=1,color="Target",linetype="Target",size="Target"))+
  scale_y_continuous(breaks = seq(0,1.1,0.2), 
                     labels = paste0(seq(0,1.1,0.2)," ‰")) +
  expand_limits(y = c(0, 1.1)) +
  labs(y="", x="") + 
  theme(plot.title = element_text(hjust = 0.5)) + 
  scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D")) +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed")) +
  scale_shape_manual(values = c(Rate = 16, Target = NA)) +
  scale_size_manual(values = c(Rate = 1, Target = .7)) +
  theme(legend.key=element_blank(),legend.position="bottom") 

图例的结果看起来很困惑:

enter image description here

我希望图例如下所示:

enter image description here

那么如何修改代码来合并图例呢?

非常感谢!

最佳答案

如果我们给图例赋予相同的名称,ggplot 将尝试合并它们:

...
scale_colour_manual(values = c(Rate = "#00BFC4", Target = "#F8766D"), name = "Legend") +
  scale_linetype_manual(values = c(Rate = "solid", Target = "dashed"), name = "Legend") +
  scale_shape_manual(values = c(Rate = 16, Target = NA), name = "Legend") +
  scale_size_manual(values = c(Rate = 1, Target = .7), name = "Legend") +
  theme(legend.key=element_blank(),legend.position="bottom") 

enter image description here

关于r - 如何合并ggplot中的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69610567/

相关文章:

R- Stat_compare_means 不适合 ggplot?

windows - 使用 Windows 资源管理器在源目录中启动 R

r - 在 ggplot2 箱线图中添加每组和子组的多个观察值

ggplot2 - 改变ggplot中的颜色

r - 突出显示图中的最高残差 : R

r - 如何在rmarkdown中的pdf_document中渲染htmlTable包中的表格?

r - ggplot2:geom_ribbon 的填充颜色行为

linux - Linux 上的 R 包管理

r - 模糊匹配两个数据框

r - ggplotly堆叠条形图过滤后未调整大小