1

I would like to create a simple mosaic plot from the data file below:

Country|Name|Count
US|Sam|10
US|John|30
UK|Sam|30
UK|John|2
CA|Sam|23
CA|Bill|45

I expect to get a mosaic plot with 1st column on x-axis and stacked rectangle of height "Count" for each category "Name".

I tried:

data<-read.table("my_table.txt", header=T, sep="|")
mosaicplot(data)

But it creates a monster with way too many columns and rows.

My question is how to mention that values of the "Count" variable should be the y values? I tried to use ftable(graph) before making the mosaic but even the table is not well ordered.

lqdo2000
  • 351
  • 2
  • 5
  • 16
  • 1
    Answering based on your title: The importing is done correctly, using str(data) you can see:'data.frame': 6 obs. of 3 variables: $ Country: Factor w/ 3 levels "CA","UK","US": 3 3 2 2 1 1 $ Name : Factor w/ 3 levels "Bill","John",..: 3 2 3 2 3 1 $ Count : int 10 30 30 2 23 45 I suggest to change your title to match your question about the mosaicplot – Freddy Dec 13 '13 at 08:54
  • [Product plots](http://vita.had.co.nz/papers/prodplots.pdf) and [How to create a Marimekko/Mosaic plot in ggplot2](http://stackoverflow.com/questions/19233365/how-to-create-a-marimekko-mosaic-plot-in-ggplot2) might be relevant. – zx8754 Dec 13 '13 at 09:14
  • Thanks! I got the principle of mosaic chart, just not the way to define "Count" as the y variable. – lqdo2000 Dec 13 '13 at 09:19
  • Although I guess there are no direct ways to do mosaics, I think a ggplot equivalent to define the data would be something like:`ggplot(data=data, aes(x=Name, y=Count, group=Country)` – lqdo2000 Dec 13 '13 at 09:24

2 Answers2

2

One possibility is to 'explode' your pre-calculated data using rep.

country <- with(df, rep(x = Country, times = Count))
name <- with(df, rep(x = Name, times = Count))

df2 <- data.frame(country, name)
mosaicplot(country ~ name, data = df2)

enter image description here

Henrik
  • 65,555
  • 14
  • 143
  • 159
1

May I suggest spine function from the vcd library:

# require(vcd)
dt <- xtabs(Count~Name+Country, data=data)
spine(dt)

?spine "Spine plots are a special cases of mosaic plots, and can be seen as a generalization of stacked (or highlighted) bar plots. Analogously, spinograms are an extension of histograms."

spineplot function is also available in the base graphics.

enter image description here

TWL
  • 2,290
  • 1
  • 17
  • 21
  • Thansk TWL! Although the axis are inverted (just need to change their order in stabs I presume), this function is very handy. – lqdo2000 Dec 13 '13 at 23:40
  • @lqdo2000, you're welcome, and indeed, try `xtabs(Count~Country+Name, data=data)` to change the order. – TWL Dec 15 '13 at 02:40