简体   繁体   English

使用R中的ggplot2为条形图添加不同的颜色

[英]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. 例如,对于Country China,一旦条形图被绘制为85,剩余的15应该以灰色绘制。 Similary for United states once bar chart is plotted for value 15 in column percent the remaining 85 should be grey color. 类似于美国一旦条形图以列百分比绘制为值15,其余85应为灰色。

Any help on this is very helpfull. 对此有任何帮助非常有帮助。 Thanks 谢谢

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

在此输入图像描述

EDIT 编辑
Based on this post , here is a way to do it with ggplot2 基于这篇文章 ,这里有一种方法可以用ggplot2

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

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM