问题描述
我可以使用此数据集来格式化图例,并在y轴上包含千位分隔符;
Data <- tibble::tribble(
~Site,~Test,~score1,~score2,~score3,"A","SD",5904,9691,NA,"B",2697,4484,"A ","MB",11418,7666,2517,6445,"C","FO",9588,"FI",5423,"NF",1527
)
我使用了这段代码;
library(dplyr)
library(tidyr)
library(ggplot2)
Data %>%
pivot_longer(cols = -c(Site,Test)) %>%
mutate(Test = factor(Test,levels = c('SD','MB','FI','FO','NF'),ordered = T)) %>%
ggplot(aes(x=Site,y=value,fill=name,legend = TRUE))+
ylim(0,20000) +
ylab("Total score") +
geom_bar(stat='identity')+
facet_wrap(.~Test,scales = 'free_x',ncol = 5,strip.position = "bottom")+
theme_minimal()+
theme(strip.placement = "outside",panel.spacing = unit(0,"points"),strip.background = element_blank(),strip.background.y = element_blank(),panel.background = element_rect(fill = "white"),panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.border = element_blank(),strip.text = element_text(face = "bold",size = 9))+
scale_color_discrete(name = "Legend",label=c("score 1","score 2","score 3"))
我无法正确标记图例,并在y值上使用千位分隔符。
解决方法
要使用正确的名称获取图例,请将scale_color_discrete
更改为scale_fill_discrete
。您正在映射到填充美学而不是颜色美学。
要获取y标签,可以添加带有某些参数的scale_y_continuous
。您可以组装标签以使其看起来像您想要的。
Data %>%
pivot_longer(cols = -c(Site,Test)) %>%
mutate(Test = factor(Test,levels = c('SD','MB','FI','FO','NF'),ordered = T)) %>%
ggplot(aes(x=Site,y=value,fill=name,legend = TRUE))+
geom_bar(stat='identity')+
facet_wrap(.~Test,scales = 'free_x',ncol = 5,strip.position = "bottom")+
theme_minimal()+
theme(strip.placement = "outside",panel.spacing = unit(0,"points"),strip.background = element_blank(),strip.background.y = element_blank(),panel.background = element_rect(fill = "white"),panel.grid.major = element_blank(),panel.grid.minor = element_blank(),panel.border = element_blank(),strip.text = element_text(face = "bold",size = 9))+
scale_fill_discrete(name = "Legend",label=c("Score 1","Score 2","Score 3")) +
scale_y_continuous(name = "Total Score",limits = c(0,20000),breaks = seq(0,20000,5000),labels = c(0,paste(seq(5000,5000)/1000,"000",sep = ",")))
,
您唯一要做的更改是:
-
ylim(0,20000)
forscale_y_continuous(labels = scales::comma_format())
-
scale_color_discrete()
代表scale_fill_discrete()
。
Data %>%
pivot_longer(cols = -c(Site,ordered = T)) %>%
ggplot(aes(x = Site,y = value,fill = name,legend = TRUE)) +
scale_y_continuous(labels = scales::comma_format()) +
ylab("Total score") +
geom_bar(stat = 'identity') +
facet_wrap(. ~ Test,strip.position = "bottom") +
theme_minimal() +
theme(strip.placement = "outside",strip.text = element_text(face = "bold",size = 9)) +
scale_fill_discrete(name = "Legend",label = c("Score 1","Score 3"))
以下是输出:
祝你好运!