首页 文章

编辑ggplot中的图例(文本)标签

提问于
浏览
82

我花了几个小时查看文档和StackOverflow,但没有解决方案似乎解决了我的问题 . 当我使用 ggplot 时,我的数据帧中有't get the right text in the legend, even though it' . 我尝试了 scale_colour_manualscale_fill_manuallabels= 的值不同,例如 c("T999", "T888")", "cols" .

这是我的代码:

T999 <- runif(10, 100, 200)
T888 <- runif(10, 200, 300)
TY <- runif(10, 20, 30)
df <- data.frame(T999, T888, TY)


ggplot(data = df, aes(x=T999, y=TY, pointtype="T999")) + 
       geom_point(size = 15, colour = "darkblue") + 
       geom_point(data = df, aes(x=T888, y=TY), colour = 'red', size = 10 ) + 
       theme(axis.text.x = element_text(size = 20), axis.title.x =element_text(size = 20),   axis.text.y = element_text(size = 20)) +
       xlab("Txxx") + ylab("TY [°C]") + labs(title="temperatures", size = 15) + 
       scale_colour_manual(labels = c("T999", "T888"), values = c("darkblue", "red")) +    theme(legend.position="topright")

帮助将非常感谢!谢谢 .

2 回答

  • 82

    @Henrik提到的教程是学习如何使用 ggplot2 包创建绘图的绝佳资源 .

    您的数据示例:

    # transforming the data from wide to long
    library(reshape2)
    dfm <- melt(df, id = "TY")
    
    # creating a scatterplot
    ggplot(data = dfm, aes(x = TY, y = value, color = variable)) + 
      geom_point(size=5) +
      labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
      scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
      theme_bw() +
      theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
            axis.text.y = element_text(size = 14), axis.title.x = element_text(size = 16),
            plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
    

    这导致:

    enter image description here

    正如评论中@ user2739472所述:如果您只想更改图例文本标签而不是ggplot默认调色板中的颜色,则可以使用 scale_color_hue(labels = c("T999", "T888")) 而不是 scale_color_manual() .

  • 26

    图例 Headers 可以通过特定的美学来标记 .

    这可以使用 ggplot2 (更多herehere)中的 guides()labs() 函数来实现 . 它允许您使用美学映射添加指南/图例属性 .

    以下是使用 mtcars 数据集和 labs() 的示例:

    ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
      geom_point() +
      labs(x="miles per gallon", y="displacement", size="horsepower", 
           col="# of cylinders", shape="# of gears")
    

    enter image description here

    使用 guides() 回答OP的问题:

    # transforming the data from wide to long
    require(reshape2)
    dfm <- melt(df, id="TY")
    
    # creating a scatterplot
    ggplot(data = dfm, aes(x=TY, y=value, color=variable)) + 
      geom_point(size=5) +
      labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
      scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
      theme_bw() +
      guides(color=guide_legend("my title"))  # add guide properties by aesthetic
    

    enter image description here

相关问题