首页 > 解决方案 > 使用 ggplot2 更改 barplot 条内的颜色

问题描述

我有以下条形图,但我只能更改边框的颜色。无论我尝试什么,我都无法更改条形图中的颜色,它仍然是灰色的。

pteddf=data.frame(x=c(0:12),runif(13),runif(13))
tidyr::pivot_longer(pteddf, -x)

colors=c("red", "blue")

ggplot(tidyr::pivot_longer(pteddf, -x),aes(-x,value,color=name,group=name))+
  geom_bar(stat="identity",position=position_dodge())+
  scale_color_manual(name="",labels = c("Negative TED","Positive TED"),
                     values= colors)+
  scale_fill_manual( values = colors)

标签: rggplot2bar-chart

解决方案


尝试这个。您可以fill在该aes()部分中使用来更改填充的颜色:

pteddf=data.frame(x=c(0:12),runif(13),runif(13))
tidyr::pivot_longer(pteddf, -x)

colors=c("red", "blue")

ggplot(tidyr::pivot_longer(pteddf, -x),aes(-x,value,
                                           fill=name,
                                           color=name,group=name))+
  geom_bar(stat="identity",position=position_dodge())+
  scale_color_manual(name="",labels = c("Negative TED","Positive TED"),
                     values= colors)+
  scale_fill_manual(name="",values = colors,
                     labels = c("Negative TED","Positive TED"))

输出:

在此处输入图像描述


推荐阅读