首页 > 解决方案 > 如何将图例添加到 ggplot

问题描述

我已经查看了在 ggplot 上绘制图例的答案。但是,这些方法似乎都不适用于我的代码,如下所示:


library(readxl)
library(ggplot2)
library(dplyr)


inputManhattan <- read_xlsx("PlotsManhattan.xlsx")
PercentMN <- inputManhattan$Percent
ComNormMN <- inputManhattan$ComNorm
ElevationMN <- inputManhattan$Elevation



ggplot(inputManhattan, aes(PercentMN, ComNormMN)) +
  geom_point(shape = 22, size = ElevationMN/20, col='orange', alpha = 0.5, fill = "grey50") +
  geom_smooth(method = "loess", se = FALSE, color = 'orange') +
  xlab("Slope") + ylab("Total Normalized Complaints") 

我得到了这张图,其中斜率是针对投诉绘制的,海拔由正方形的大小表示: Manhattan Plot

我希望我的图例是:“高程 = 正方形的大小”,或者如果我可以在我的图例中使用插图,那就太好了。

但我什至无法让传奇出现。我会很感激任何帮助谢谢。

一些数据值: 数据

标签: rggplot2plotlegend

解决方案


你有没有尝试过:

ggplot(inputManhattan, aes(Percent, ComNorm)) + 
    geom_smooth(method = "loess", se = FALSE, color = 'orange') + 
    geom_point(
        aes(size = Elevation/20), 
        shape = 22, 
        col = 'orange', 
        alpha = 0.5, 
        fill = "grey50") + 
    xlab("Slope") + 
    ylab("Total Normalized Complaints") 

inputManhattan数据集中的任何列名都放在aes().
在我上面的示例代码中,您不需要PercentMN,ComNormMNElevationMN.

我使用数据集运行了类似的代码mtcars并得到了一个图例:

ggplot(mtcars, aes(disp, mpg)) + 
    geom_smooth(method = "loess", se = FALSE, color = 'orange') + 
    geom_point(
        aes(size = wt/20), 
        shape = 22, 
        col = 'orange', 
        alpha = 0.5, 
        fill = "grey50")

ggplot 示例


推荐阅读