R barplot与分组

时间:2018-01-26 14:38:25

标签: r

我检查了ggplot规格,看起来我需要转置我的数据来构建条形图,或者仍然有一个选项可以与该df一起使用,所以我实际上可以在分组中使用列名,我为下面的demo演示了图像,在ggplot上仍然无法获得我们分组的位置,或者我们可以用逗号列出它们? Tx all

df1 <-  data.frame(yy=2017,  F1=23, F2=40, F3=4)
df2 <-  data.frame(yy=2018,  F1=16, F2=90, F3=8)
df <- rbind(df1,df2)
df 
    yy F1 F2 F3
1 2017 23 40  4
2 2018 16 90  8

ggplot(df, aes(F1, yy)) +   ## this is just bad sample
  geom_bar(aes(fill = yy), stat = "identity", position = "dodge")

enter image description here

1 个答案:

答案 0 :(得分:2)

library(tidyverse)

df1 <-  data.frame(yy=2017,  F1=23, F2=40, F3=4)
df2 <-  data.frame(yy=2018,  F1=16, F2=90, F3=8)
df <- rbind(df1,df2)

df %>% 
  gather(type,value,-yy) %>%           # reshape data
  mutate(yy = factor(yy)) %>%          # update variable to a factor
  ggplot(aes(type, value, fill=yy)) +
  geom_bar(stat = "identity", position = "dodge")

enter image description here