您的因子水平未与因子顺序的更改进行映射。
请注意,我对你的进行了更改df
这样在重新排序时它确实会发生变化,变化是在Amount
column.
df <- data.frame(x=1:4, Type = c("Metals", "Foodstuff", "Textiles", "Machinery"),
myColour = c('blue', 'red', 'green', 'orange'), Amount = c(50, 75, 25, 5))
帮自己一个忙,加载 tidyverse
library(tidyverse)
然后使用theme_set
theme_set(theme_classic()+
theme(panel.grid.major.x = element_line(colour = 'grey60', linetype = 'dashed'),
panel.grid.major.y = element_line(colour = 'grey60', linetype = 'dashed'),
axis.ticks.y = element_blank(),
axis.text.x = element_text(colour = 'black', size = 16),
axis.ticks.x = element_line(colour = 'grey60'),
axis.ticks.length = unit(3, "mm"),
aspect.ratio = (600/450),
axis.title.x=element_blank(),
axis.title.y=element_blank()))
然后,您可以“破解”并重新调整因素(也许不是最好的方法,但可以完成)。
df %>% arrange(Amount) %>%
mutate(myColour = factor(myColour, myColour),
Type = factor(Type, Type)) -> df1
这样就可以更轻松地提取颜色级别作为绘图向量。
mycols <- as.vector(levels(df1$myColour))
然后绘制
ggplot(df1, aes(Type, Amount, color = myColour, fill = myColour)) +
geom_bar(stat = 'identity', position = 'dodge', show.legend = FALSE, width = .85) +
theme(axis.text.y = element_text(colour = mycols, size = 18, face = 'bold')) +
coord_flip() +
scale_fill_manual(values = mycols) +
scale_color_manual(values = mycols)
希望这对你有用。
这是无效的原始编辑,因此可以忽略:更改df$myColour
to myColour
在代码中的两个实例中。
有了这么多主题调整,您应该真正考虑使用theme_set
以及。