Home > Mobile >  R ggplot bar chart: bars colors won't change
R ggplot bar chart: bars colors won't change

Time:03-17

Say, the following code:

x_axe<-c(1,2,3)
y_axe_a<-c(10,20,30)
y_axe_b<-c(100,200,300)

for_barchart<-data.frame(x_axe, y_axe_a, y_axe_b)

chart<-ggplot(data=for_barchart, aes(x=x_axe, y=y_axe_a, color=x_axe))  
  geom_bar(stat="identity", fill = x_axe, show.legend = FALSE, width = 0.75) 
  ylim(0,45) 
  ylab("so and so")

I want the bars of certain colors but:

chart   scale_fill_manual(values=c("yellow", "red", "blue"))

the plot is created but with the default colors, not those specified. Anyone understands why?

CodePudding user response:

It's a simple matter of assigning an order to the different colours in a column.

for_barchart<-data.frame(x_axe, y_axe_a, y_axe_b)

for_barchart$colors=c("yellow", "red", "blue")
for_barchart$colors<-factor(for_barchart$colors, levels=c("yellow", "red", "blue"))

library(ggplot2)

(chart<-ggplot(data=for_barchart, aes(x=x_axe, y=y_axe_a))  
        geom_bar( aes(fill = colors),stat="identity", show.legend = FALSE, width = 0.75) 
        scale_fill_manual(values=c("yellow", "red", "blue")) 
        ylim(0,45) 
        xlab("Groups") 
        ylab("so and so")) 
        theme_minimal()

Plot:

enter image description here

Sample data:

 x_axe<-c(1,2,3)
 y_axe_a<-c(10,20,30)
 y_axe_b<-c(100,200,300)

Other solution would be if x_axe<-c(1,2,3) are defined as characters x_axe<-c("1","2","3")

Sample code:

(chart<-ggplot(data=for_barchart, aes(x=x_axe, y=y_axe_a, fill=x_axe))  
  geom_bar(stat="identity", show.legend = FALSE, width = 0.75) 
  scale_fill_manual(values=c("1"="yellow", "2"="red", "3"="blue")) 
  ylim(0,45) 
  xlab("Groups") 
  ylab("so and so")) 
  theme_minimal()

Sample data:

 x_axe<-c("1","2","3")
 y_axe_a<-c(10,20,30)
 y_axe_b<-c(100,200,300)
  • Related