【问题标题】:How to add custom series labels to a legend in R's ggplot?如何将自定义系列标签添加到 R 的 ggplot 中的图例?
【发布时间】:2010-02-26 06:54:28
【问题描述】:

我有一个情节(示例代码粘贴在下面),我试图通过自己的标签添加系列信息。而不是绘制“p1s1”“p1s2”“p3s4”,我想要“治疗1”“治疗2”“治疗3”。我使用levels(series_id) 来获取唯一的系列名称,并使用查找表来获取描述。 (我认为这会让它们按照绘制的顺序排列?)我将这些描述放在一个名为treatment_descriptions 的向量中。

从文档中我认为我应该在这里使用比例尺,但我无法弄清楚是哪一个,或者如何做到这一点。类似于: scale_something(name="Treatment Descriptions", breaks=NULL, labels=treatment_descriptions, formatter=NULL) ?但是这应该去哪里呢?

library(ggplot2)

# Create a long data.frame to store data...
growth_series = data.frame ("read_day" = c(0, 3, 9, 0, 3, 9, 0, 2, 8), 
"series_id" = c("p1s1", "p1s1", "p1s1", "p1s2", "p1s2", "p1s2", "p3s4", "p3s4", "p3s4"),
"mean_od" = c(0.6, 0.9, 1.3, 0.3, 0.6, 1.0, 0.2, 0.5, 1.2),
"sd_od" = c(0.1, 0.2, 0.2, 0.1, 0.1, 0.3, 0.04, 0.1, 0.3),
"n_in_stat" = c(8, 8, 8, 8, 7, 5, 8, 7, 2)
)

> # Now gives us some example long form data...
> > growth_series 
>  read_day series_id mean_od sd_od        n_in_stat   
>   1       p1s1     0.6      0.10         8 2       
>   3       p1s1     0.9      0.20         8 3    
>   9       p1s1     1.3      0.20         8 4    
>   0       p1s2     0.3      0.10         8 5    
>   3       p1s2     0.6      0.10         7 6    
>   9       p1s2     1.0      0.30         5 7    
>   0       p3s4     0.2      0.04         8 8    
>   2       p3s4     0.5      0.10         7 9    
>   8       p3s4     1.2      0.30         2 2

# Plot using ggplot...
ggplot(data = growth_series, aes(x = read_day, y = mean_od, group = series_id, color = series_id)) +
geom_line(size = 1.5) +
geom_point(aes(size = n_in_stat)) +
geom_errorbar(aes(ymin = mean_od - sd_od, ymax = mean_od + sd_od), size = 1, width = 0.3) +
xlab("Days") + ylab("Log (O.D. 730 nm)") +
scale_y_log2() +
scale_colour_hue('my legend', breaks = levels(growth_series$series_id), labels=c('t1', 't2', 't3'))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    也许你可以重新标记你的因素?

    growth_series$series_id <- factor(
         growth_series$series_id, 
         labels=c('treatment 1', 't2', 't3'))
    

    或者如果你还在寻找scale_something,它应该是scale_colour_hue()

    ... + scale_colour_hue('my legend', 
       breaks = levels(growth_series$series_id), 
       labels=c('t1', 't2', 't3'))
    

    【讨论】:

    • 谢谢,第一个建议有效,第二个无效,我暂时保留这个问题,因为我认为应该有更好的方法来做到这一点。我的描述很长,所以把它们放在桌子上看起来真的很难看,但我想我不必在绘制之前把它们放在桌子上,所以没什么大不了的。干杯,约翰
    • 第二个有什么问题?顺便说一句,“...”代表你的 ggplot() + geom_line + .. + scale_y_log2 组
    • 当然,我试过了,但出现语法错误,对你有用吗?
    • 它对我有用。如果没有人分享其他解决方案,您介意将您运行的命令附加到您的问题中吗?
    • 谢谢,现在有效,在我认为之前一定是一个隐藏字符,当从 Stackoverflow 复制粘贴时。非常感谢
    猜你喜欢
    • 2021-01-05
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多