如何仅将ggplot图例的某些元素设为斜体?

How to italicize only some elements of ggplot legend?

我需要将图例的所有元素设置为斜体,而不是最后一个(“其他”)。 我当前的图形设计代码是:

p <- ggplot(D, aes(x=factor(Habitat, levels=c("Water","Soil")), y=RA, fill=factor(Species)))+
  geom_bar(stat = "identity", position = "stack", width = 0.5, colour='black', size=0.1)+
  scale_fill_manual(name="Species", values=myColour)+
  guides(fill=guide_legend(ncol=1))+
  xlab(" ")+
  ylab("[ % ]")+
  ylim(0,100)+
  theme(aspect.ratio=2,
        panel.background = element_rect(fill = "white"),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size=35, face="bold", vjust = 0, hjust = -0.1),
        legend.title = element_text(size=35, colour = "black", face="bold"),
        legend.text = element_text(size=35, colour = "black"),
        legend.key.size = unit(1, 'cm'),
        legend.key = element_rect(size = 15, color = "white"),
        legend.key.height = unit(2, "cm"),
        legend.key.width = unit(2, "cm"),
        legend.box.spacing = unit(1.5, "cm"),
        axis.title = element_text(size=30, face="bold"),
        axis.title.x = element_text(vjust = -3),
        axis.text = element_text(size=25, colour = "black"),
        axis.line = element_line(colour = "black", size = 0.9))+
  guides(fill = guide_legend(override.aes = list(linetype = "solid", color = "white", size = 5))))

使用scale_fill_manual,我没有找到任何其他示例。 谢谢

使用 ggtext 包,您可以将 markdown 应用于文本元素。在 markdown 中,你可以通过用星号 * 将它们包围起来来将它们变为斜体。鸢尾花数据集示例:

library(ggplot2)
library(ggtext)

df <- transform(iris, Species = as.character(Species))
# Introduce a dummy "Other" category by sampling 50 observations
df$Species[sample(nrow(df), 50)] <- "Other"
# Conditionally apply markdown if Species is not "Other"
df$Species <- with(df, ifelse(Species == "Other", "Other", 
                              paste0("*Iris ", Species, "*")))

ggplot(df, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(colour = Species)) +
  theme(legend.text = element_markdown()) # <- Set plot theme element

或者,您可能希望将降价格式化步骤作为一个函数提供给比例的 label 参数。如果您对应该保留的颜色进行了一些排序,这会很方便。

df <- transform(iris, Species = as.character(Species))
df$Species[sample(nrow(df), 50)] <- "Other"

ggplot(df, aes(Sepal.Length, Sepal.Width)) +
  geom_point(aes(colour = Species)) +
  scale_colour_discrete(
    labels = function(x) {
      ifelse(x == "Other", "Other", paste0("*Iris ", x, "*"))
    }
  ) +
  theme(legend.text = element_markdown())