在r中绘制堆栈图表

问题描述 投票:0回答:1

我想在R中绘制一个堆栈图:我的数据集如下所示,称为df:

df <- structure(list(id = c("A","B"),
                   x1 = c(10,30),
                   x2 = c(20,40),
                   x3 = c(70,30)), row.names = 1:2,
                   class = "data.frame")

    df<- melt(df, id.vars = "id")
library(ggplot2)
ggplot(data = df, aes(x = variable, y = value, fill =id)) + 
  geom_bar(stat = "identity") +
  xlab("\nCategory") +
  ylab("Percentage\n") +
  guides(fill = FALSE) +
  theme_bw()

输出不是我想要的输出,

我想在x轴上看到id,在堆叠列中看到x1,x2,x3。

r ggplot2 reshape2
1个回答
4
投票

ggplot的x总是指定x轴,fill是你想要对数据进行分类的变量。因此,要创建所需的绘图,代码为:

    library(reshape2) ## for melt()
    library(ggplot2)

    df<- melt(n_df, id.vars = "id")

    ggplot(data = n_df, aes(x = id, y = value, fill =variable)) + 
      geom_bar(stat = "identity") +
      xlab("\nCategory") +
      ylab("Percentage\n") +
      guides(fill = FALSE) +
      theme_bw() 

Output:

如果你想让传奇出现,你必须guides(fill = TRUE)

Second Plot

© www.soinside.com 2019 - 2024. All rights reserved.