R ggplot2 用 2 个 hlines 和正确的图例绘制单个数据

标签 r plot ggplot2 legend

在 Axeman 的帮助下,我已经能够用平均/中值线绘制一个数据。为了完成注释,我想将平均值/中值放入图例标签中。我的代码:

require(data.table)
require(ggplot2)
wf <- data.table::fread('Date Gals Days  GpD    GpM
                     2016-10-21  6.0    1  6.0  186.0
                     2016-10-22  6.0    1  6.0  186.0
                     2016-10-23 12.4    1 12.4  384.4
                     2016-10-24 26.8    1 26.8  830.8
                     2016-10-25 33.3    1 33.3 1032.3
                     2016-10-26 28.3    1 28.3  877.3')
nmu <- mean(wf$Gals)
textmu <- paste("Mean:", round(nmu, 2))
nmed <- median(wf$Gals)
textmed <- paste("Median:", round(nmed, 2))

p <- ggplot(wf, aes(Date, Gals)) +  
     geom_line(aes(lty = "Gals", color = "Gals", group = 1)) +
     geom_hline(aes(yintercept = nmu,  linetype = textmu, color = textmu), 
                color='red',size=1)+
     geom_hline(aes(yintercept = nmed, linetype = textmed, color = textmed), 
                color='orange',size=1)+
     #scale_linetype('Water Usage') +
     scale_color_manual('Water Usage', 
                        values=c('Gals'='black',textmu='red', textmed='orange')) +
     xlab("") + 
     ylab("Gallons per Day")

print(p)

产生:
enter image description here

我该如何纠正?

最佳答案

准备一个标签向量,然后使用我在 previous answer 中提供的代码:

labels <- c(Gals = 'Gals',
            Mean = paste("Mean:", round(mean(wf$Gals), 2)),
            Median = paste("Median:", round(median(wf$Gals), 2)))

ggplot(wf, aes(Date, Gals)) +  
  geom_line(aes(lty = "Gals", color = "Gals", group = 1)) +
  geom_hline(aes(yintercept = mean(wf$Gals), linetype = "Mean", color = "Mean"), size=1) +
  geom_hline(aes(yintercept = median(wf$Gals), linetype = "Median", color = "Median"), size = 1) +
  scale_linetype('Water Usage', labels = labels) +
  scale_color_manual(
    'Water Usage', 
    values = c('Gals' = 'black', 'Mean' = 'red', 'Median' = 'orange'),
    labels = labels
  ) +
  xlab("") + ylab("Gallons per Day")

enter image description here

关于R ggplot2 用 2 个 hlines 和正确的图例绘制单个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070246/

相关文章:

r/sciplot : overlapping whiskers in lineplot. CI

python - 绘制一个圆-matplotlib

r - R 中的 ggplot2 : annotate outside of plot and underline text

r - 将第二个标题添加到基于极坐标的 ggplot2 图

javascript - 将变量传递给 Jquery Plot 数据

r - 多元线性回归 : Plot a straight line with confidence intervals

r - 使用 ggforce facet_zoom 操纵 y 轴比例

r - 如何循环遍历 R 中的 CSV 文件文件夹

ROCR 包不适用于 R 3.4.4

plot - gnuplot - 平滑插值 x=f(y)