简体   繁体   中英

R. Use frequency of a correlation to set dot size in plot

Is it possible to use the frequency of a correlationn to set the cex value in a plot? eg using mtcars. The correlation between cyl and carb. table:

    cyl
carb 4 6 8
   1 5 2 0
   2 6 0 4
   3 0 0 3
   4 0 4 6
   6 0 1 0
   8 0 0 1

How can I use the values (eg 1 for 8 carb & 8 cyl) to set the size of the dots in an R?

The code is quite simple (I'm only new)

plot(mtcars$cyl, mtcars$carb,
    pch = 20,
    bty = "L",
    cex = what goes here????,
    col = carb.col[cyl],
    lines(lowess(cyl, carb),
    col = "red", lwd = 3)
)

I would prefer ggplot , but here's a base solution:

dat = data.frame(with(mtcars, table(cyl, carb)))
dat = subset(dat, Freq > 0)
dat[] = lapply(dat, function(x) as.numeric(as.character(x)))

plot(dat$cyl, dat$carb,
    pch = 20,
    bty = "L",
    cex = dat$Freq,
    #col = carb.col[cyl],
    lines(lowess(mtcars$cyl, mtcars$carb),
    col = "red", lwd = 3)
)

在此处输入图片说明

If you wanted to use the code more generally, you'd probably want to scale the cex so it has a maximum size...

Here's a fully reproducible ggplot solution:

library(ggplot2)

ggplot(subset(reshape2::melt(table(mtcars$carb, mtcars$cyl)), value > 0)) + 
  geom_point(aes(Var1, Var2, size = value)) + 
  scale_y_continuous(breaks = c(4, 6, 8), name = "cyl") + 
  scale_x_continuous(name = "carb") + 
  scale_size(range = c(2, 8)) +
  theme_bw()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM