如何将图例添加到ggplot

时间:2020-11-10 01:19:41

标签: r ggplot2 plot legend

我仔细研究了在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

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

但是我什至无法得到一个传说。感谢您的帮助。

一些数据值: Data

1 个答案:

答案 0 :(得分:0)

您尝试过吗:

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()内。
在上面的示例代码中,您不需要PercentMNComNormMNElevationMN

我使用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 example