GGPLOT堆叠条形顺序

时间:2018-01-31 00:56:04

标签: r ggplot2

big_theme <- theme(
  panel.background=element_rect(fill = "black"),
  plot.background =element_rect(fill = "black", colour = NA),
  plot.title = element_text(hjust=0.5, size=15, color="white"),
  axis.text.y=element_text(colour="white", size=14),
  axis.title.x = element_text(colour = "white", size=14),
  axis.title.y = element_text(colour = "white", size=14),
  axis.text.x=element_text(vjust=1, angle=45, color="white", size=14, hjust=1),
  strip.background =element_rect(fill="black"),
  strip.text = element_text(colour = 'white'),
  strip.text.y = element_text(angle=0), 
  legend.position = "top"
)

theme2 = theme(panel.background = element_rect(fill = 'black'),
  legend.background=element_rect(fill="black"),
  legend.text = element_text(colour="white", size=14), 
  legend.justification = "right",
  legend.key.height = unit(1, "line"),
  legend.key = element_rect(color="black", fill="black"))

theme3 = theme(plot.background = element_rect(fill = 'black'))

plot1 <- ggplot(sample_data) + big_theme + theme2 + theme3
plot1 + geom_col(aes(x=category, y=value, fill=variable, color=variable)) + 
  scale_fill_manual(values=c("#000000", "#D3667C", "#53AC79")) + 
  scale_color_manual(values=c("#00A2EF", "#D3667C", "#53AC79"))

我有一个看起来像的数据集:

category    variable    value
a   x   1.2
b   x   1.05
c   x   1.11
a   y   1.43
b   y   1.09
c   y   0.97
a   z   1.12
b   z   1.46
c   z   1.32

我希望条形图和图例的ggplot中的顺序为z,x,y。我试图使用一个订单变量来做到这一点但是当我在我的美学中使用订单时它不起作用。所以a的条形是未填充的,而b和c是未填充的。

1 个答案:

答案 0 :(得分:0)

你可以将variable改为c("z", "x", "y")

plot1 + geom_col(aes(x=category,y=value,
  fill=forcats::fct_relevel(variable, c("z", "x", "y")),
  color=forcats::fct_relevel(variable, c("z", "x", "y")))) + 
  scale_fill_manual(values=c("#000000","#D3667C","#53AC79")) + 
  scale_color_manual(values=c("#00A2EF","#D3667C","#53AC79"))

希望这会有所帮助。

相关问题