r - ggplot 图例 - 更改标签、顺序和标题

标签 r ggplot2

我正在努力修改情节中的图例。这是一个可重现的示例:

dtt <- structure(list(model = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("ma", "mb", "mc"), class = "factor"), year = c(2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L, 2005L, 2006L, 2007L, 2008L, 2009L, 2010L), V = c(0.16, 0.14, 0.11, 0.13, 0.15, 0.16, 0.24, 0.17, 0.12, 0.13, 0.15, 0.15, 0.2, 0.16, 0.11, 0.12, 0.12, 0.15), lower = c(0.11, 0.11, 0.07, 0.09, 0.11, 0.12, 0.16, 0.12, 0.04, 0.09, 0.09, 0.11, 0.14, 0.1, 0.07, 0.08, 0.05, 0.1), upper = c(0.21, 0.19, 0.17, 0.17, 0.19, 0.2, 0.29, 0.23, 0.16, 0.17, 0.16, 0.2, 0.26, 0.27, 0.15, 0.16, 0.15, 0.19)), .Names = c("model", "year", "V", "lower", "upper"), class = "data.frame", row.names = c(NA, -18L))

我的情节是这样生成的:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
    geom_ribbon(alpha = 0.35, linetype=0)+ 
    geom_line(aes(linetype=model), size = 1.5) +       
    geom_point(aes(shape=model), fill = "white", size = 4)  +      
    theme(legend.position=c(.6,0.8)) +
    theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid'))

产生这个: enter image description here

现在我想做的是

  1. 更改图例的标题
  2. 更改图例项目的显示顺序
  3. 更改图例项的文本。

我已经摆弄了几个小时试图做到这一点,但没有取得多大成功。到目前为止,我所做的最好的就是添加以下内容:

scale_colour_hue(name = "Model 1",
    breaks=c("mb", "ma", "mc"),
    labels=c("MBB", "MAA", "MCC"))

但它会产生这种令人厌恶的现象: enter image description here

如您所见,现在多了一个不需要的图例,并且图例中的形状与图中的形状不匹配!

最后,我想在图例中用图形来表明蓝色和绿色的线是虚线,而不是实线 - 但我根本不知道该怎么做。

任何帮助将不胜感激,

最佳答案

你需要做两件事:

  1. 在绘图前重命名因子水平并重新排序
  2. 将每个图例的标题重命名为相同的标题

代码:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

但是,我认为这确实很难看并且难以解释。使用构面要好得多:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

关于r - ggplot 图例 - 更改标签、顺序和标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12075037/

相关文章:

R - 来自数据框中两个子集的新变量,行中的随机顺序

r - 如何使用非默认浏览器?

r - 如何将 ggplot 旋转为横向?

r - 如何更改ggplot2中面板(灰色区域)的纵横比

r - 在 R 中使用 gganimate 创建绘图动画的问题

R,编织器和源函数: How to preserve source file comments for html report

r - 如何简化R中的角度(以度为单位)?

r - 如何在 golem 框架 Shiny 包中测试模块?

r - ggplot alpha = 0 不工作

r - 生成堆积累积平滑频率分布图