如何更改 r 中的标签文本?

How to change the label text in r?

我正在学习 r,我在设置标签文本(所需文本)和调整图例标题的大小和粗体方面遇到问题。我试图从 Whosebug 中的其他来源找到一些帮助,它需要输入 scale_color_hue 来更改标签文本,但我不知道该放在哪里。这是我的数据框:

dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  class = c("a","a","b","b","c","a","b","b","c","c","c","a","a","b","b","b","c","c"))

这是我进行更改的代码:

library(dplyr)
library(ggplot2)
dat %>% 
  filter(time %in% c("Breakfast", "Dinner")) %>%
  droplevels %>%
  count(time, class) %>% 
  group_by(time) %>% 
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = fct_reorder(class,prop), y = prop, fill = time, label = scales::percent(prop))) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
  scale_y_continuous(labels = scales::percent)+
  coord_flip() +
  theme(legend.position="top", legend.direction="vertical")+
  guides(fill = guide_legend(title = "Time",nrow = 1))+
  coord_flip()

对于标题Time,我可以设置将其更改为我们想要的文本,但我不知道如何设置它的字体大小以及如何将其设置为粗体。对于 BreakfastDinner 之类的标签文本,我无法将其设置为所需的文本。

如有任何帮助,我们将不胜感激。谢谢!

根据您想要实现的目标,您有多种选择。

此回答仅解决您关于图例标题的问题。

包含图例标题的典型方法是在 ggplot::labs 函数中命名用于对图例键进行分组的审美,例如 labs(fill = "Time")。 @Edward 指出的另一种方法是使用 theme


dat <- data.frame(
  time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Lunch","Lunch","Lunch","Lunch","Lunch","Lunch","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner","Dinner"), levels=c("Breakfast","Lunch","Dinner")),
  class = c("a","a","b","b","c","a","b","b","c","c","c","a","a","b","b","b","c","c"))


library(dplyr)
library(ggplot2)
library(forcats)


g0 <- dat %>% 
  filter(time %in% c("Breakfast", "Dinner")) %>%
  droplevels %>%
  count(time, class) %>% 
  group_by(time) %>% 
  mutate(prop = n/sum(n)) %>%
  ggplot(aes(x = fct_reorder(class, prop), y = prop, fill = time, label = scales::percent(prop))) +
  geom_col(position = 'dodge') +
  geom_text(position = position_dodge(width = 0.9), vjust = 0.5, size = 3) + 
  scale_y_continuous(labels = scales::percent)+
  coord_flip()

g1 <- g0+
  labs(fill = "Time")+
  theme(legend.position = "top",
        legend.direction = "vertical",
        legend.title = element_text(hjust = 0.5))

g1


g2 <- g0+
  labs(fill = "Time")+
  theme(legend.position = "top",
        legend.direction = "vertical",
        legend.title = element_text(hjust = 0.5, face = "bold", size = 20))
g2

g1 给你:

g2 给你:

粗体图例标题,在主题中加上face="bold"。 对于图例标签,使用 scale_fill_discrete(labels=...).

所以,

...
  theme(..., legend.title=element_text(hjust = 0.5, face="bold", size=14)) +
  scale_fill_discrete(labels=c("Label 1","Label 2"))