1
votes

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

2

2 Answers

3
votes

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")
0
votes

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