首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何仅对ggplot图例的某些元素进行斜体显示?

如何仅对ggplot图例的某些元素进行斜体显示?
EN

Stack Overflow用户
提问于 2021-03-10 20:27:51
回答 1查看 186关注 0票数 0

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

代码语言:javascript
复制
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时,我找不到任何其他示例。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-10 20:51:19

使用ggtext包,您可以将标记应用于文本元素。在markdown中,您可以通过用星号*将部件括起来来设置斜体。虹膜数据集的示例:

代码语言:javascript
复制
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参数的函数提供。如果您对应该保留的颜色引入了一些排序,这会很方便。

代码语言:javascript
复制
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())
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66564799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档