【问题标题】:How to italicize only some elements of ggplot legend?如何仅将ggplot图例的某些元素斜体?
【发布时间】:2021-03-10 12:27:50
【问题描述】:

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

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,我没有找到任何其他示例。 谢谢

【问题讨论】:

    标签: r ggplot2 legend italic


    【解决方案1】:

    使用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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 2021-09-14
      • 1970-01-01
      • 2021-03-30
      相关资源
      最近更新 更多