[英]How to change legend title and key order and colour to a multi-stacked barplot in R with ggplot2
我正在使用 R 到一個多層條形圖,我想更改圖例的名稱並編輯相關變量的顏色(我更喜歡藍色調色板)。
但是,我一直試圖編輯圖例和顏色是徒勞的。 我想知道你能不能幫幫我!
以下是我到目前為止使用的代碼。
library(ggthemes)
library(tidyverse)
library(reshape2)
theme_set(theme_classic())
multiBP <- data.frame(Countries = c('Romania','Hungary','Spain','Italy','poland','Greece','France','Finland','Germany','Denmark','Netherlands','Sweden'),
worried_emigration <- c(0.55, 0.39, 0.34, 0.32, 0.30, 0.28, 0.14, 0.14, 0.08, 0.06, 0.06, 0.04),
both <- c(0.26, 0.34, 0.38, 0.35, 0.30, 0.54, 0.31, 0.20, 0.29, 0.12, 0.15, 0.14),
immigration <- c(0.10, 0.2, 0.19, 0.24, 0.27, 0.07, 0.25, 0.44, 0.31, 0.53, 0.55, 0.47),
neitherdontknow <- c(0.09, 0.07, 0.09, 0.09, 0.13, 0.11, 0.30, 0.22, 0.32, 0.29, 0.24, 0.35))
data.m <- melt(multiBP, id.vars='Countries')
data.m['value'] <- data.m['value']*100
levels(data.m$variable) <- c("% Worried about emigration", "% Worried both immigration and emigration",
"% Worried about immigration", "% Neither / don't know")
data.m$variable <- factor(data.m$variable, levels = c("% Worried about emigration", "% Worried about immigration",
"% Worried both immigration and emigration", "% Neither / don't know" ))
# ggplot(arrange(mdat,variable,desc(value)), aes(variable, value, fill=day)) +
ag<-filter(data.m, variable == "% Worried about emigration")
data.m$Countries <- factor(data.m$Countries, levels=ag$Countries[order(ag$value)], ordered = TRUE)
# ggplot(arrange(mdat,variable,desc(value)), aes(variable, value, fill=day)) +
ggplot(arrange(data.m, variable, desc(value), Countries), aes(fill = forcats::fct_rev(variable), Countries, value))+
geom_bar(position = 'stack', stat = 'identity', colour='grey')+
expand_limits(x=c(0,0))+
coord_flip()+
labs(title="Multiple Time Series Chart",
subtitle="BLA BLA ",
caption="Source: The Guardian")+
# guide_legend(title= 'TItolo')+
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
geom_text(aes(label=paste0((value),"%")),
position=position_stack(vjust=0.5),size=3)
這讓我回想起:
library(ggplot2)
arrange(data.m, variable, desc(value), Countries) %>%
ggplot(aes(Countries, value, fill = fct_rev(variable)))+
geom_bar(position = 'stack', stat = 'identity' ) +
scale_fill_brewer(guide = guide_legend(reverse = TRUE), palette = "Blues") +
geom_text(aes(label = paste0(value,"%")), position = position_stack(vjust = 0.5), size = 3)+
coord_flip()+
labs(title = "Multiple Time Series Chart",
subtitle = "BLA BLA ",
caption = "Source: The Guardian",
fill = "Legend Title")+
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid'))
給你:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.