简体   繁体   中英

draw stack chart in r

I want to draw a stack chart in R : My data set is as follows called 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()

The out put is not the one that I want,

I want to to see id in the x axis and x1,x2,x3 in the stacked column.

ggplot's x always specifies the x-axis, fill the variable you want to categorize your data by. So to create your desired plot, the code is:

    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() 

输出:

If you want to have the legend show up, you have to guides(fill = TRUE) :

第二图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM