在R中创建分组条形图

在R中创建分组条形图,r,plot,bar-chart,R,Plot,Bar Chart,我在R中有一个数据帧df,看起来像这样: 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 100 | _ _ _ _ _ _ _ _ _ _ _ _ |_ _ _ _ _ _

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

        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
100 |               _ _ _ _ _ _    _ _ _ _ _ _
    |_ _ _ _ _ _   | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
 0  |_|_|_|_|_|_|__|_|_|_|_|_|_|__|_|_|_|_|_|_|_
     D C B E K R    D C B E K R    D C B E K R
         Rd             Sw            Sf
100 |  _ _   _ _
    |_| | |_| | |
    | | | | | | |
    | | | | | | |
    | | | | | | |
 0  |_|_|_|_|_|_|_
     D C B E K R
       x label
我试图用条形图来绘制数据。我需要y轴的范围是0-100,x轴是类别名称。基本上,我需要它看起来像这样:

        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
100 |               _ _ _ _ _ _    _ _ _ _ _ _
    |_ _ _ _ _ _   | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
    | | | | | | |  | | | | | | |  | | | | | | |
 0  |_|_|_|_|_|_|__|_|_|_|_|_|_|__|_|_|_|_|_|_|_
     D C B E K R    D C B E K R    D C B E K R
         Rd             Sw            Sf
100 |  _ _   _ _
    |_| | |_| | |
    | | | | | | |
    | | | | | | |
    | | | | | | |
 0  |_|_|_|_|_|_|_
     D C B E K R
       x label
所有Ds颜色相同,所有Cs颜色相同,依此类推

我不知道该怎么做,也不知道该使用哪些库

到目前为止,我已经:

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)
我不知道为什么我只得到这个


任何帮助都将不胜感激。

看起来您不希望使用data.frame中的列向量调用as.matrix——很可能您需要:as.matrix(D),例如:

barplot(as.matrix(data.frame(rpois(10, 2), rpois(10, 1))), beside = T)
基本上,我举一个简单的例子,假设你有:

df = data.frame(x = c(1,2,3), y = c(2,3,4))
您在做as.matrix(df$x,df$y)-这不是您想要的,您想要做:as.matrix(df),因此:

我会给你你想要的。关键是看一下“as.matrix”的功能。

试试这个:

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

通过这样做df:
df2@user3043867-你是什么意思?您可以清楚地看到我的示例有两组标签!是否也有方法在条形图中显示实际值?重塑2是解决此类问题的方法。理想情况下,每个数据点在数据帧中应有自己的行(长格式)。这是通过整形程序包中的melt命令实现的。
df <- read.table(sep=" ", header=T, text="
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")

df$facet <- row.names(df)
library(reshape2)
df.long <- melt(df, "facet")
ggplot(df.long, aes(x=variable, y=value, fill=variable)) + 
  geom_bar(stat="identity", position="dodge") + 
  facet_wrap(~facet, ncol=3)