user3719979
user3719979

Reputation: 163

Adding a different color to the barplot using ggplot2 in R

I have a data set as below

 data=data.frame(Country=c("China","United States",
                 "United Kingdom",
                 "Brazil",
                 "Indonesia",
                 "Germany"), 
       percent=c(85,15,25,55,75,90))

and code for the same is

     names = data$Country

     barplot(data$percent,main="data1", horiz=TRUE,names.arg=names,    
             col="red")

I would like to add a grey color to the bar plot after the given values is plotted.

Say for example for Country China once the bar graph is plotted for 85 the remaining 15 should be plotted in Grey color. Similary for United states once bar chart is plotted for value 15 in column percent the remaining 85 should be grey color.

Any help on this is very helpfull. Thanks

Upvotes: 1

Views: 292

Answers (2)

Cath
Cath

Reputation: 24074

You can do:

# create a variable containing the "complementary percentage"
data$compl <- 100 - data$percent
# plot both the actual and complementary percentages at once, with desired colors (red and grey)
barplot(as.matrix(t(data[, c("percent","compl")])), main="data1", horiz=TRUE, names.arg=names, col=c("red","grey"))

enter image description here

EDIT
Based on this post, here is a way to do it with ggplot2

library(reshape)
melt_data <- melt(data,id="Country")
ggplot(melt_data, aes(x=Country, y=value, fill=variable)) + geom_bar(stat="identity")

Upvotes: 3

CoderGuy123
CoderGuy123

Reputation: 6679

I didn't see a built in method of doing this. Here's a hack version.

data$grey = c(rep(100,6)) #new data to fill out the lines
par(mar=c(3,7.5,3,3)) #larger margin on the right for names
barplot(data$grey, horiz=TRUE, #add barplot with grey filling
        xlim=c(0,100),las=1,xaxt="n", #no axis
        col="grey") #grey
par(new=TRUE) #plot again
barplot(data$percent,main="data1", horiz=TRUE,names.arg=names, #plot data
        xlim=c(0,100),las=1, #change text direction and set x limits to 1:100
        col="red")

enter image description here

Upvotes: 0

Related Questions