我正在学习r,在设置标签文本(所需文本)以及调整图例标题的大小和粗体方面遇到问题。我试图从stackoverflow的其他来源中找到一些帮助,它需要使用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", legend.title=element_text(hjust = 0.5))+
guides(fill = guide_legend(title = "Time", nrow = 1))
对于标题Time
,我可以设置将其更改为所需的文本,但是我不知道如何设置其喜欢的大小以及将其设置为粗体。对于Breakfast
和Dinner
这样的标签文本,我无法将其设置为所需的文本。
对此将提供任何帮助。谢谢!
您有多种选择,取决于您想要实现的目标。
此答案仅解决您有关图例标题的问题。
[包含图例标题的典型方法是通过在ggplot::labs
函数中命名用于对图例键进行分组的美学名称,例如labs(fill = "Time")
。
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)
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() +
labs(fill = "Time")+
theme(legend.position="top",
legend.direction="vertical",
legend.title=element_text(hjust = 0.5))
哪个给您: