Creating a bar chart within another bar chart

Asked

Viewed 774 times

5

I look for a very efficient and useful way to use the nested bar charts. A mode where you can demonstrate divisions and subdivisions in the same graph. How to generate such a graph in R?

  • 2

    John, this question had been closed because the staff thought it was unclear what was being asked. We reopened. However, to try to avoid this type of closure, when asking a question of this type, sometimes it is interesting to put an example of what you want to achieve (such as the graphic itself that you put in the answer!), or more details than you want. Here’s a discussion that might be helpful, Hugs! http://meta.pt.stackoverflow.com/questions/824/como-crea-um-exemplo-m%C3%Adnimo-reproduces%C3%Advel-em-r/825#825

  • I get it, Carlos, thank you very much! I’ll keep this in mind next time. !

1 answer

6

inserir a descrição da imagem aqui

To produce the chart above just follow the example below:

install.packages('ggplot2')
library(ggplot2)
install.packages("reshape")
library(reshape)
install.packages("scales")
library(scales)

#.................
# Exemplo de dados

df <- read.csv(textConnection("Segment,Alpha,Beta,Gamma,Delta
                                 A,1416649,590270,236108,118054
                                 B,708325,531243,354162,177081
                                 C,354162,354162,236108,236108
                                 D,147568,147568,147568,147568"))
closeAllConnections()

#.........................................................
# Colocando tudo em uma mesma escala e rotulando os eixos

dfa <- melt(df, id = c("Segment"), variable_name = "Company")

#...................
# Tratando do eixo Y

ylim <- max(cast(dfa, Company ~ ., sum)[, 2],
            cast(dfa, Segment ~ ., sum)[, 2])

#.........
# Plotando

p <- ggplot(dfa) + scale_y_continuous(limits = c(0,ylim), breaks = NULL)
p1 <- p + geom_bar(aes(Company, value), stat = "identity",breaks = NULL)
(p2 <- p1 + geom_bar(aes(Company, value, fill = Segment),
                     stat = "identity",breaks = NULL, position = "dodge"))
  • 1

    Personally, I don’t like that kind of chart. I think the same information can be visualized in the stacked bar graph, which also makes it easier to compare the distribution of subgroups between groups. (http://docs.ggplot2.org/current/geom_bar-16.png).

  • 1

    Daniel, it’s just another graphical alternative. I like this one that you presented and also this one that I put in the answer. Depending on where you publish, newspaper, internet, magazine, one style or another can be the most enjoyable for the interpretation of readers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.