我需要一个看起来如下的组合栏图:
使用如下示例数据集:
With IT background, No IT background
9,1
2,10
7,1
2,0
我尝试使用ggplot
但是无法获得任何可行的解决方案
答案 0 :(得分:3)
以下是基础R的答案,
IT_data <- data.frame(c(9,2,7,2),
c(1,10,1,0))
colnames(IT_data) <- c("With IT background","No IT background")
rownames(IT_data) <- c("Aware of Risks","Not Aware of Risks","Care About","Do Not Care About")
barplot(as.matrix(IT_data), beside=TRUE,
col=rainbow(4),
legend.text=rownames(IT_data), args.legend=list(x="topleft"))
使用以下代码
可以改善图例的位置和大小barplot(as.matrix(IT_data), beside=TRUE,
col=rainbow(4),
legend.text=rownames(IT_data), args.legend=list(x="center",cex=0.7,bty="n"))
更接近OP的请求。
答案 1 :(得分:2)
我认为您正在寻找以下代码。我非常同意上述评论者的意见,请始终让您的代码可以重现,并在您寻求帮助时提供数据。在这种情况下,我花了一分钟来复制你的数据帧,但想象你有200个值?
library(ggplot2)
library(dplyr)
library(reshape2)
#recreate the data frame
data<- data.frame(With.IT.background=c(9,2,7,2),
No.IT.background=c(1,10,1,0))
#attach rownames
rownames(data)<- c("Aware of Risks",
"Not Aware of Risks",
"Care About", "Do Not Care About")
#make rownames a column (dplyr does not send rownames through pipe)
data %>% mutate(Awareness=rownames(data)) -> data
data %>% melt() %>% ggplot(data=., mapping=aes(x=Awareness,
y=value, fill=Awareness)) +
geom_bar(stat="identity") + theme_bw() +
theme(axis.text.x= element_blank(), axis.ticks.x=element_blank())+
ylab("Answers") + xlab("With IT Background") +
facet_wrap(~variable) +xlab("")
答案 2 :(得分:0)
示例数据
Answers <- c(1,10,1,0, 9,2,7,2)
IT <- c(rep("With.IT.background",4), rep("No.IT.background",4))
Risks <- c("Aware of risks", "Not aware of risks", "Care about", "Do not care about")
data <- data.frame(cbind(IT, Risks, Answers))
更改列类型
data$Answers <- as.numeric(as.character(data$Answers))
data$Risks <- factor(data$Risks, levels = c("Aware of risks","Not aware of risks", "Care about", "Do not care about"))
并绘制
library(ggplot2)
ggplot(data, aes(x=factor(Risks), y=Answers, fill=factor(Risks))) +
geom_bar(stat="identity") + facet_grid(. ~ IT) +
ggtitle("Awareness and risks") + guides(fill=guide_legend(title=NULL)) +
labs(x = "") + theme(axis.text.x = element_blank()) + # remove xlab and tickers
theme(legend.position=c(.5,.7)) + # put the legend inside
theme(legend.background=element_blank()) + # Remove overall border
theme(legend.key=element_blank()) # Remove border around each item