How to create cluster column chart in R? [duplicate]

走远了吗. 提交于 2020-01-17 01:41:05

问题


I need to plot the ratios of 2 categories over 4 groups in order of a nice easy understandable comparison.

i did this so far and got 2 plots:

x <- c(0.50, 0.53, 0.49, 0.47)
names(x) <- c("Mütter über Söhne", "Mütter über Töchter", "Väter über Söhne", 
              "Väter über Töchter")
barplot(x, xlab= "Gruppe", ylab = "Anteil Wörter abstrakt-logisch ", main = 
        "abstrakt-logisch")

x1 <- c(0.51, 0.54, 0.46, 0.49)
names(x1) <- c("Mütter über Söhne", "Mütter über Töchter", "Väter über Söhne", "Väter über Töchter")
barplot(x1, xlab= "Gruppe", ylab = "Anteil Wörter kreativ-verbal ", main = "kreativ-verbal")

I want to compare the ratios of words in 2 categories over 4 groups. so first ratio from category 1 (0.50) compared to first ratio of category 2 (0.51) over the group "Mütter über Söhne". i also need a naming for x-axis = "groups" and y-axis = "ratios of words". it should look something like that:

Can someone help me with that?


回答1:


If you are not familiar with ggplot2, you can use this basic way.

x1 <- c(0.50, 0.53, 0.49, 0.47)
x2 <- c(0.51, 0.54, 0.46, 0.49)
group <- c("group1", "group2", "group3", "group4")

plot.new()
plot.window(xlim = c(1, 20), ylim = c(0, 0.6))
abline(h = 0:6/10, col = "grey")
barplot(rbind(x1, x2), beside = T, space = c(0.5, 2), axes = F,
        col = c("grey10", "grey"), xlab = "groups", ylab = "ratios of words",
        names.arg = group, add = T)
legend(x = "topright", legend = c("category 1", "category 2"),
       fill = c("grey10", "grey"), box.col = NA)
mtext(0:6/10, side = 2, at = 0:6/10)

space is specified by two numbers, where the first is the space between bars in the same group, and the second the space between the groups.




回答2:


Here is the correct answer of yours. You need to first define your dataset in a proper way:

dt<-data.frame(
  group= c("Mütter über Söhne", "Mütter über Töchter", "Väter über Söhne", "Väter über Töchter"),
  category=c("category1","category1","category1","category1",    "category2","category2","category2","category2"),
  ratio= c(0.50, 0.53, 0.49, 0.47,  0.51, 0.54, 0.46, 0.49))

head(dt)

And then use the ggplot to draw it

    library(ggplot2)


ggplot(data=dt, aes(x=group, y=ratio, fill=category)) +
  geom_bar(stat="identity", position=position_dodge())+
  scale_fill_brewer(palette="Paired")+                #Remove background
  theme(axis.line = element_line(colour = "black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        panel.border = element_blank(),
        panel.background = element_blank())

and the final output is:



来源:https://stackoverflow.com/questions/52015997/how-to-create-cluster-column-chart-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!