ggplot2绘图参数

图例

  1. 删除图例: theme(legend.position = "none")
  2. 删除图例标题: theme(legend.title = element_blank());guides(color = guide_legend(title = NULL))
  3. 修改图例标题: labs(legend_title = "")
  4. 修改图例名称: scale_fill_manual(labels = c("A" = "A1"))
  5. 修改图例大小: guides(color = guide_legend(override.aes = list(size = 4)))
  6. 图例位置: theme(legend.position = "bottom")
  • 图例在图外的上下左右位置: “top”,”bottom”,”left”,”right”
  • 图例在图内左上的位置: theme(legend.position = c(0, 1), legend.justification = c(0, 1))

坐标轴

  1. 坐标轴文字倾斜: theme(axis.text.x = element_text(angle = 45, hjust = 1)) theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
  2. 修改坐标轴文本及范围: scale_y_continuous(expand = c(0,0), limits = c(0, 1), breaks = c(0,0.25,0.5,0.75,1), label = c("0%","25%","50%","75%","100%"))
  3. 修改坐标轴标题: labs(x = "", y = "", title = "")
  • 标题含有表达式: labs(x = expression(log[2]*'FoldChange', y = expression(-log[10]*'pvalue')))

自定义颜色形状大小

  1. 分类型变量: scale_color_manual(values = c("Up"="#b40000","Down"="#004377","Ns"="#bdbdbd"))
  2. 连续型变量: scale_color_gradientn(values = seq(0, 1, 0.2), colors = c("#39489f","#39bbec","#f9ed36","#f38466","#b81f25"))
  3. 形状: scale_shape_manual(values = c("up-triangle" = 17, "down-triangle" = 25, "circle" = 16))
  4. 大小: scale_size_continuous(range = c(0, 1))

主题

  1. 透明背景的主题:
  • theme_minimal
    有网格线, 无坐标轴, 坐标轴文本为灰色
    1
    2
    3
    4
    5
    6
    7
    8
    9
    theme_minimal(base_size = 12) +
    theme(panel.grid = element_blank(),
    axis.text = element_text(face = "bold", color = "black"),
    axis.title = element_text(face = "bold"),
    legend.title = element_text(face = "bold"),
    legend.text = element_text(face = "bold"),
    axis.ticks = element_line(size=1.3),
    panel.border = element_rect(linewidth = 1.8, linetype = "solid", color = "black", fill = NA),
    plot.title = element_text(face = "bold", hjust = 0.5))
  • theme_cowplot
    cowplot包的主题,有坐标轴
    1
    2
    3
    4
    5
    6
    7
    8
    theme_cowplot(font_size = 12) + 
    theme(axis.text = element_text(face = "bold"),
    axis.title = element_text(face = "bold"),
    legend.title = element_text(face = "bold"),
    legend.text = element_text(face = "bold"),
    axis.ticks = element_line(size=1.3),
    axis.line = element_line(size=1.5),
    plot.title = element_text(face = "bold", hjust = 0.5))

保存图片

  • ggsave(“.png”, p, width = 8, height = 8, dpi = 300)
Author: Giftbear
Link: https://giftbear.github.io/2024/10/30/ggplot2绘图参数/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.