ZT:改动ggplot2中的某些标签

original address:https://www.datanovia.com/en/blog/how-to-change-ggplot-labels/

library(ggplot2) 
theme_set(theme_classic())
#Create a basic plot using the dataset ToothGrowth:

# Convert the variable dose from numeric to factor variable
ToothGrowth$dose <- as.factor(ToothGrowth$dose)

# Create a boxplot colored by dose group levels
bxp <- ggplot(ToothGrowth, aes(x = dose, y = len)) + 
  geom_boxplot(aes(color = dose)) +
  scale_color_manual(values = c("#00AFBB", "#E7B800", "#FC4E07"))
bxp

Key R functions

labs(..., title = waiver(), subtitle = waiver(), caption = waiver(),
  tag = waiver())

xlab(label)

ylab(label)

ggtitle(label, subtitle = waiver())

A list of new name-value pairs. The name should be an aesthetic. For example p + labs(title = "Main title", x = "X axis label", y = "Y axis label") changes main title and axis labels.
title: plot main title.
subtitle: the text for the subtitle for the plot which will be displayed below the title.
caption: the text for the caption which will be displayed in the bottom-right of the plot by default.
tag: the text for the tag label which will be displayed at the top-left of the plot by default.
label: the title of the respective axis (for xlab() or ylab()) or of the plot (for ggtitle()).

Add titles and axis labels

In this section, we’ll use the function labs() to change the main title, the subtitle, the axis labels and captions.

It’s also possible to use the functions ggtitle(), xlab() and ylab() to modify the plot title, subtitle, x and y axis labels.

Add a title, subtitle, caption and change axis labels:

bxp <- bxp + labs(title = "Effect of Vitamin C on Tooth Growth",
              subtitle = "Plot of length by dose",
              caption = "Data source: ToothGrowth",
              x = "Dose (mg)", y = "Teeth length",
              tag = "A")
bxp

Modify legend titles

You can use labs() to changes the legend title for a given aesthetics (fill, color, size, shape, . . . ). For example:

Use p + labs(fill = "dose") for geom_boxplot(aes(fill = dose))
Use p + labs(color = "dose") for geom_boxplot(aes(color = dose))
and so on for linetype, shape, etc

bxp + labs(color = "Dose (mg)")

Split long titles

If the title is too long, you can split it into multiple lines using \n. In this case you can adjust the space between text lines by specifying the argument lineheight in the theme function element_text():

bxp + labs(title = "Effect of Vitamin C on Tooth Growth \n in Guinea Pigs")+
  theme(plot.title = element_text(lineheight = 0.9))

你可能感兴趣的:(ZT:改动ggplot2中的某些标签)