我有一个数据集如下
data=data.frame(Country=c("China","United States",
"United Kingdom",
"Brazil",
"Indonesia",
"Germany"),
percent=c(85,15,25,55,75,90))
和相同的代码是
names = data$Country
barplot(data$percent,main="data1", horiz=TRUE,names.arg=names,
col="red")
我想在绘制给定值后为条形图添加灰色。
例如,对于Country China,一旦条形图被绘制为85,剩余的15应该以灰色绘制。类似于美国一旦条形图以列百分比绘制为值15,其余85应为灰色。
对此有任何帮助非常有帮助。 感谢
答案 0 :(得分:3)
你可以这样做:
# 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"))
修改强>
基于this post,以下是使用ggplot2
library(reshape)
melt_data <- melt(data,id="Country")
ggplot(melt_data, aes(x=Country, y=value, fill=variable)) + geom_bar(stat="identity")
答案 1 :(得分:0)
我没有看到这样做的内置方法。这是一个黑客版本。
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")