How to use italics for facet labels in ggplot2?

2020-03-24 07:56发布

问题:

I am trying to use italics for facet names in ggplot2. I am first ordering and renaming the facets. I have come across a potential solution, but this requires labeller=label_parsed and I am using labeller=name_labeller to rename my facets.

In the following example, I would like the facet names "one" "two" "three" "four" and "five" to be italicized. Here is an example dataframe:

structure(list(Names = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L, 5L, 
5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L), Other = c(5L, 
3L, 2L, 6L, 5L, 4L, 5L, 4L, 5L, 3L, 2L, 6L, 5L, 4L, 5L, 4L, 4L, 
5L, 3L, 2L), X = c(0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 
0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L), Y = c(0L, 10L, 
0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 0L, 10L, 
0L, 10L, 0L, 10L)), .Names = c("Names", "Other", "X", "Y"), class = "data.frame", row.names = c(NA, 
-20L))

and the code to produce the plot is

library(ggplot2)
library(grid)
vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)



facets <- c("1", "2", "3", "4", "5")

names <- list(
  '1'="one",
  '2'="two",
  '3'="three",
  '4'="four",
  '5'="five"
)

name_labeller <- function(variable,value){
  return(names[value])
}

ggplot(FacetTestData[FacetTestData$Names %in% facets,], aes(y = Y, x = X, group = Names)) + 
  geom_point(shape = 21, size=3) + 
  scale_fill_manual(values=c("gray90","gray40")) + 
  geom_smooth(method="lm", se= FALSE, size = 1) +
  scale_color_manual(values=c("black","black")) +
  geom_smooth(method = 'lm', size = 1, colour = 'red', se = FALSE)  +
  facet_grid(Names ~ ., labeller=name_labeller)

The following code appears to give italics attributes to the list names

levels(names) <- c("italic('one')", "italic('two')", "italic('three')", "italic('four')",    "italic('five')")

but I can't quite figure out how to make this work with facet_grid(). Does anyone know how I can do this?

回答1:

Something along these lines should work:

... + theme(strip.text = element_text(face = "italic"))

See the docs for more detail about theme().



回答2:

You can separate the axes graphics using the code from krlmlr and modifying

... + theme(strip.text = ...   

to

... + theme(strip.text.x = ...    

OR

... + theme(strip.text.y = ...


标签: r ggplot2