How to assign specific colors in ggplot R

2

I am working with a database and I want to make a barplot in which each column is related to a variable, and I want to assign each column a specific color, and not the one chosen by default by ggplot.

These are the data I have:

    Abstencion    PP    PSOE    IU    UPyD   Ahora.madrid Ciudadanos Year
1      40.86     27.79  20.20  5.72   0.00         0.00       0.00  a91
2      28.87     37.35  19.62 11.02   0.00         0.00       0.00  a95
3      39.94     29.54  21.49  5.17   0.00         0.00       0.00  a99
4      31.07     35.21  25.18  4.95   0.00         0.00       0.00  a03
5      34.09     36.48  20.28  5.69   0.00         0.00       0.00  a07
6      32.78     32.79  15.79  7.09   5.18         0.00       0.00  a11
7      31.15     23.62  10.44  1.16   1.25        21.76       7.81  a15

What I want is to make a barplot according to the year, and that each column is the color of the match.

For this, I have this vector with the colors:

col <- c("black","dodgerblue","firebrick1","chartreuse3",
         "deeppink","darkorchid3","darkorange1")

And I created this code (assuming the previous matrix is called X). I'm new to ggplot so maybe there's a better way to do it:

library(ggplot2)
library(reshape2)
a <- X[1,]
a.molten <- melt(a, value.name="Votes", variable.name="Party")
#Eliminar los partidos politicos que sacaron 0 votos
a.molten <- a.molten[-which(a.molten$Votes==0),] 
ggplot(a.molten, aes(x=Party, y=Votes, fill=Party)) + geom_bar(stat="identity")

changing the parameter of a < - X [i,] I get the barplots of each year, but what I need now is to know how to assign to each game the color collected in the vector col

    
asked by Alvaro 07.06.2016 в 11:53
source

1 answer

2

To add specify colors given by fill you must use and add scale_fill_manual(values = col) for the fill. You can also use color next to scale_color_manual(values = col) to modify the borders.

The colors will be added following the order of the factors of the variable Party .

ggplot(a.molten, aes(x=Party, y=Votes, fill=Party,  color=Party)) + 
  geom_bar(stat="identity") +
  scale_fill_manual(values = col) +
  scale_color_manual(values = col)
    
answered by 17.06.2016 в 18:00