【问题标题】:ggplot2 - Labels below line plotggplot2 - 线图下方的标签
【发布时间】:2019-08-21 17:42:47
【问题描述】:

请考虑以下代码:

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"))

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

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以为每个值分配一个向量到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"))
    

    【讨论】:

    • 让代码更通用的小建议:each = length(unique(data_long$cyl)))
    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 2022-01-18
    相关资源
    最近更新 更多