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个条形(列),彼此相邻,表示x1
,x2
和x3
每个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))
答案 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")
# 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)
答案 1 :(得分:0)