> For the complete documentation index, see [llms.txt](https://zpliu.gitbook.io/booknote/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zpliu.gitbook.io/booknote/ggplot2/tu-li.md).

# 自定义图例

```r
ggplot(data=data1,aes(x=genome,y=isoformCount,fill=type))+
  geom_bar(stat = "identity")+
  guides(
    fill=guide_legend(
      direction = 'vertical',
      title=NULL,
      label.theme=element_text(angle = 90,size = 20), ##修改图例label的角度和大小
      label.vjust = 1.2,
      label.position='top',
      reverse=F))
```

## **图例函数：**

* `guide_colorbar()`/`guide_colourbar()` 用于连续变量的图例
* `guide_legend()` 用于离散变量的图例,也可以用于连续变量
* `guides()` 将\_colorbar和\_legend嵌套进去，方便映射，如`guides(fill = guide_colorbar())`

  可以在`scale_xxx()`标度中指定guide类型，guide = "colorbar"或guide = “legend”

## fill映射

使用`guide_legend`修改图例的各个部件：

* `direction`修改图片的方向
* `title`图例标题
* `label.theme`使用`element_text`对文字颜色、大小、方向进行修改
* `label.position`在图例处的位置
* `reverse`是否翻转图例

## 修改图例label

```r
##修改由填充导致的图例  
scale_fill_manual(values = c(
    "#f6e58d", "#ffbe76"
  ),
  labels = c("conserved", "nonconserved")
  )
```

## 修改图例位置

* 使用位置坐标
* 或者使用关键字 `top`、`bottom`等

```r
theme(
legend.position = c(0,1) ##调整图例位置
)
```

## 修改图例中图形属性

* 多个重叠图例时，只需要指定相同的title，自动的就合并在一起了

```r
  guides(
    alpha=guide_legend(
      title = 'Feature ratio'
    ),
    size=guide_legend(
      title = 'Feature ratio',
      override.aes = list(size=5,color='red')
    ),
    color=guide_legend(
      title='Type'

    ),
    shape=guide_legend(
      title='Type',
      override.aes = list(size=5)
    )
  )
```
