在R中创建分组的条形图 [英] Creating a grouped bar plot in R

查看:145
本文介绍了在R中创建分组的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有一个数据帧df,看起来像这样:

I have a data frame df in R, that looks like this:

        D     C     B     E     K     R
Rd      80    80    80    80    80    80
Sw      100   100   100   100   100   100
Sf      100   100   100   100   100   100

我正在尝试以条形图绘制数据.我需要y轴的范围为0-100,x轴为类别名称.基本上,我需要它看起来像这样:

I'm trying to plot the data in a bar plot. I need the y axis to have the range 0-100, and the x axis to be the category names. Basically, I need it to look like this:

100 |               _ _ _ _ _ _    _ _ _ _ _ _
    |_ _ _ _ _ _   | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
 0  |_|_|_|_|_|_|__|_|_|_|_|_|_|__|_|_|_|_|_|_|_
     D C B E K R    D C B E K R    D C B E K R
         Rd             Sw            Sf

所有D都具有相同的颜色,所有C都具有相同的颜色,依此类推.

With all of the Ds the same color, all of the Cs the same colour, and so on.

我不确定如何执行此操作或使用哪个库.

I'm not sure how to do this, or which libraries to use.

到目前为止,我有:

counts <- as.matrix(df$D, df$C, df$B, df$E, df$K, df$R)

barplot(counts, beside = TRUE, space = c(0, 0, 0, 0, 0, 0), xlab = "",
col = c("coral", "coral1", "coral2", "coral3", "coral4", "cornflowerblue"),
    names.arg = c("D", "C", "B", "E", "K", "R"))
mtext(side = 1, text = "x label", line = 7)

但是它仅显示如下内容:

But it only displays something like this:

100 |  _ _   _ _
    |_| | |_| | |
    | | | | | | |
    | | | | | | |
    | | | | | | |
 0  |_|_|_|_|_|_|_
     D C B E K R
       x label

我不确定为什么只得到这个.

I'm not sure why I'm getting only this.

任何帮助将不胜感激.

推荐答案

尝试一下:

df2 <- t(as.matrix(df))
bp <- barplot(df2,beside=TRUE,col=1:6)
mtext(rownames(df2),1,at=bp)

如果您想编辑内容以旋转轴标签或精确定位组/条标签,则可以执行以下代码.更改line=参数以影响标签的垂直位置,并更改barplot调用上的las=1参数以根据需要旋转标签.

If you would like to edit things to spin axis labels or exactly position the group/bar labels, then you can do something like the below code. Change the line= arguments to affect the vertical position of the labels and the las=1 argument on the barplot call to spin the labels as required.

df2 <- t(as.matrix(df))
bp <- barplot(df2,beside=TRUE,col=1:6,axisnames=FALSE,las=1)
mtext(rownames(df2),1,at=bp,line=0.6)
mtext(colnames(df2),1,at=colMeans(bp),line=2)

这篇关于在R中创建分组的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆