我想创建一个水平条形图来比较我的两个表。我已经进行了比较并创建了一个比率表。
这是数据的样子:
> dput(data)
structure(list(Name=c('Mazda RX4','Mazda RX4 Wag','Datsun 710','Hornet 4 Drive',
'Hornet Sportabout','Valiant','Duster 360','Merc 240D','Merc 230','Merc 280','Merc 280C',
'Merc 450SE','Merc 450SL','Merc 450SLC','Cadillac Fleetwood','Lincoln Continental',
'Chrysler Imperial','Fiat 128','Honda Civic','Toyota Corolla'),ratio=c(1.393319198903125,
0.374762569687951,0.258112791829808,0.250298480396529,1.272180366473129,0.318000456484454,
0.264074483447591,0.350798965144559,2.310541690719624,1.314300844213157,1.18061486696761,
0.281581177092538,0.270164442687919,2.335578882236703,2.362339701969396,1.307731925943769,
0.347550384302281,0.232276047899868,0.125643566969327,0.281209747680576),Freq=c(2L,9L,2L,2L,
4L,2L,2L,3L,3L,5L,2L,2L,2L,7L,2L,4L,4L,2L,2L,4L)),.Names=c('Name','ratio','Freq'),class=
'data.frame',row.names=c(NA,20L))
我想实现类似的目标:
在中间,我会把1.根据计算出的比例,我想把适当的比例放到右边的3到例如0到左边(当然可以是不同的)。
每辆车都应该有一个单独的酒吧。它将在这个图上给出20个小节。
另外一件事就是将第Freq
栏中的数字放在图上。它不是强制性的,但会有所帮助。
答案 0 :(得分:4)
我真的没有看到这个情节对你的数据有多大意义,因为没有数量加起来为1(或共同的总数)。比例可能有意义,而不是比例。我可能会遗漏一些东西......也许你正在寻找这样的东西?
library(ggplot2)
r <- range(d$ratio)
br <- seq(floor(r[1]), ceiling(r[2]), 0.5)
ggplot(d, aes(x = Name, y = ratio - 1)) +
geom_bar(stat = 'identity', position = 'identity') +
coord_flip() +
ylab('ratio') + xlab('car') +
scale_y_continuous(breaks = br - 1, labels = br) +
theme_bw()
为右侧的标签添加geom_text(aes(label = Freq), y = r[2] - 0.95)
。
或者如果你想将值1居中(有点棘手):
r <- range(d$ratio)
m <- ceiling(max(abs(range(d$ratio))))
br <- seq(-m + 1, m - 1, 0.25)
ggplot(d, aes(x = Name, y = ratio - 1)) +
geom_bar(stat = 'identity', position = 'identity') +
geom_text(aes(label = Freq), y = m - 1.1) +
coord_flip() +
ylab('ratio') + xlab('car') +
scale_y_continuous(breaks = br, labels = br + 1, limits = c(-m + 1, m - 1),
expand = c(0, 0)) +
theme_bw()
答案 1 :(得分:3)
## plot precomputations
yexpand <- 0.2;
barheight <- 0.8;
xlim <- c(0,3);
xticks <- seq(xlim[1L],xlim[2L],0.25);
ylim <- c(1-barheight/2-yexpand,nrow(data)+barheight/2+yexpand);
yticks <- seq_len(nrow(data));
cols <- c('#6F7EB3','#D05B5B');
## draw plot
par(mar=c(5,4,4,2)+0.1+c(0,3,0,0));
plot(NA,xlim=xlim,ylim=ylim,xaxs='i',yaxs='i',axes=F,ann=F);
segments(xlim[1L],ylim[1L],xlim[1L],ylim[2L],xpd=NA);
axis(1L,xticks,cex.axis=0.7);
axis(2L,yticks,data$Name,las=2L,cex.axis=0.7);
mtext(expression(italic(Ratio)),1L,3);
mtext(expression(italic(Car)),2L,5.5);
mtext(data$Freq,4L,0.75,at=yticks,las=2L,cex=0.7);
y1 <- seq_len(nrow(data))-barheight/2;
y2 <- seq_len(nrow(data))+barheight/2;
rect(xlim[1L],y1,data$ratio,y2,col=cols[1L],lwd=0.5);
rect(data$ratio,y1,xlim[2L],y2,col=cols[2L],lwd=0.5);
abline(v=1);