Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting a categorical variable against another categorical variable

Tags:

plot

r

I am comparing different clustering methods and I would like to see if two different methods (or sets of parameters) are defining similar clusters or not. My clusters are defined as categorical factors (categorical variables) in a data frame.

If I use plot() with x being a categorical variable and y being a continuous variable I get a box plot. If I do the same but y being another categorical variable I get some weird bar plot (figure below). How do you interpret this king of plot?

plot you get when plotting a categorical variable against another categorical variable

In this plot,x (df$category1) has 13 levels:

[1] "A" "B" "C" "D" "cluster1" "cluster5" [7] "cluster2" "cluster8" "cluster0" "cluster6" "cluster4" "cluster3" [13] "cluster7"

and y (df$category2) has only 12 levels :

[1] "A" "B" "C" "D" "cluster5" "cluster0" [7] "cluster4" "cluster2" "cluster3" "cluster6" "cluster1" "cluster7"

A, B, C, and D are the same between the two columns, the rest if clusters are not necessarily the same as are the result of different clustering runs.

Edit : the code used was plot(df$category1, df$category2)

like image 958
pedrosaurio Avatar asked Aug 07 '26 14:08

pedrosaurio


2 Answers

When x and y are both factors, plot calls spineplot. Example from that function's help page:

treatment <- factor(rep(c(1, 2), c(43, 41)), levels = c(1, 2),
    labels = c("placebo", "treated"))
improved <- factor(rep(c(1, 2, 3, 1, 2, 3), c(29, 7, 7, 13, 7, 21)),
    levels = c(1, 2, 3),
    labels = c("none", "some", "marked"))

spineplot(improved, treatment)

Though this looks a little different to the plot you have.

like image 57
Richie Cotton Avatar answered Aug 10 '26 05:08

Richie Cotton


Not what you asked, but try mosaicplot(). It'll produce a graphic suitable for two categorical variables.

like image 22
Manoel Galdino Avatar answered Aug 10 '26 06:08

Manoel Galdino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!