我如何在一个情节中将多个条形图组合在一起

时间:2017-08-10 08:04:30

标签: r ggplot2 geom-bar

data1 <- as.data.frame(aggregate(x=Vezarat[c("x1" , "x2" , "x3")]
                                 ,by=Vezarat[c("InsurerType")]
                                 ,FUN="mean"))

大家好。我有一个名为Vezarat的数据库,并使用聚合函数作为上面的代码:

data1

insurerType     x1      x2      x3
 a              12      14       15
 b              10      15       10
 c               7      23        0

现在我希望有一个条形图,x.axis显示保险公司类型,每个保险公司类型都有3个条形(列),彼此相邻,表示x1x2x3每个insurertyp e的值,例如"a"。然后是"b"的3个条,依此类推。 我怎么能用ggplot()+geom_bar

得到这个情节

非常感谢任何一点帮助。

数据:

structure(list(insurerType = structure(1:3, .Label = c("a", "b", 
"c"), class = "factor"), x1 = c(12L, 10L, 7L), x2 = c(14L, 15L, 
23L), x3 = c(15L, 10L, 0L)), .Names = c("insurerType", "x1", 
"x2", "x3"), class = "data.frame", row.names = c(NA, -3L))

2 个答案:

答案 0 :(得分:2)

您可以尝试:

# read your data
d <- read.table(text="insurerType     x1      x2      x3
 a              12      14       15
 b              10      15       10
 c               7      23        0", header=T)

# load ggplot2 and dplyr within 
library(tidyverse)
# transform the data using dplyr and tidyr and plot the bars using fill to
# get the three bars per insurer. I used geom_col as it uses stat_identity as default  
d %>%
  gather(key, value, -insurerType) %>% 
  ggplot(aes(x=insurerType, y=value, fill = key)) +
    geom_col(position = "dodge")

enter image description here

# Another solution would be to use a facet like this:
d %>%
  gather(key, value, -insurerType) %>% 
  ggplot(aes(x=key, y=value, fill=key)) +
    geom_col(position = "dodge") +
    facet_wrap(~insurerType)

enter image description here

答案 1 :(得分:0)

首先重塑数据

library(reshape2)

df2 = melt(df)

然后绘制

library(ggplot2)

ggplot(data=df2, aes(x=insurerType, y=value, fill=variable)) +
     geom_bar(stat="identity", color="black", position=position_dodge())+
     theme_minimal()

enter image description here