首页 > 解决方案 > ggplot2 - 线图下方的标签

问题描述

请考虑以下代码:

library(ggplot2)

data<-mtcars
data$hp2<-mtcars$hp+50

data_long <- reshape2::melt(data[c('cyl', 'hp', 'hp2')], id.vars = 'cyl')
head(data_long)

ggplot(data_long, aes(x = cyl, y = value, colour = variable)) +
  stat_summary(fun.y = mean, geom = "line", show.legend = FALSE) + 
  stat_summary(fun.y = mean, geom = "text", show.legend = FALSE,  vjust=-0.7, aes( label=round(..y.., digits=0))) +
  scale_color_manual(values = c("red", "blue"))

是否有可能改变红色曲线的文本标签的行为?即在红线下方显示它们?

标签: rggplot2

解决方案


您可以vjust=为每个值分配一个向量以分配其位置。

ggplot(data_long, aes(x = cyl, y = value, colour = variable)) +
  stat_summary(fun.y = mean, geom = "line", show.legend = FALSE) + 
  stat_summary(fun.y = mean, geom = "text", show.legend = FALSE,  
               vjust= rep(c(1.4, -0.7), each = 3), aes( label=round(..y.., digits=0))) +
  scale_color_manual(values = c("red", "blue"))

在此处输入图像描述


推荐阅读