Reputation: 391
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.
Upvotes: 1
Views: 2537
Reputation: 2300
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.
Upvotes: 1
Reputation: 67778
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)
Upvotes: 2