我想在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。
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()
如果你想让传奇出现,你必须guides(fill = TRUE)
: