使用 R 中的绘图可视化交叉表

问题描述 投票:0回答:3

我看到在 excel 中生成了一个绘图,我想知道 R 是否也可以做到这一点。this picture is essentially a visualization of a crosstab table comparing the days of the week to preferred meals on that day and counting the number of people that fall within those categories

这张图片本质上是一个交叉表的可视化,将一周中的几天与当天的首选膳食进行比较,并计算属于这些类别的人数。

我怎样才能制作这样的情节?

r pivot-table bubble-chart
3个回答
26
投票

使用 Hadley Wickham 的

ggplot2

library(ggplot2)                           

# Set up the vectors                           
days <- c("Mon","Tues","Wed","Thurs","Fri")
slots <- c("Coffee/Breakfast","Lunch","Happy Hour","Dinner")

# Create the data frame
df <- expand.grid(days, slots)
df$value <- c(1,1,1,1,2,1,1,NA,NA,1,4,4,7,4,1,5,6,14,5,1)    

#Plot the Data
g <- ggplot(df, aes(Var1, Var2)) + geom_point(aes(size = value), colour = "green") + theme_bw() + xlab("") + ylab("")
g + scale_size_continuous(range=c(10,30)) + geom_text(aes(label = value))

enter image description here

您关心轴线穿过圆圈吗?此外,绿色略有不同,标签文本是黑色而不是白色。


1
投票

ggmosaic 包扩展了

ggplot
以提供替代方案。

library(ggplot2)
library(ggmosaic)

# Set up the vectors                           
days <- c("Mon","Tues","Wed","Thurs","Fri")
slots <- c("Coffee/Breakfast","Lunch","Happy Hour","Dinner")

# Create the comporessed data frame
df <- expand.grid(days, slots, stringsAsFactors = TRUE)
df$value <- c(1,1,1,1,2,1,1,0,0,1,4,4,7,4,1,5,6,14,5,1)    
df.expanded <- df[rep(row.names(df), df$value), 1:2]

#Plot the Data
ggplot(data = df.expanded) +
  geom_mosaic(aes(x = product(Var2,Var1), fill = Var2)) + 
  ggsave("mosaic.png")

0
投票

只需添加一种利用优秀的

ggpubr
包的替代方法:

# Load ggpubr package
library(ggpubr)

## Borrowed from Tommy O'Dell's answer
# Set up the vectors                           
days <- c("Mon", "Tues", "Wed", "Thurs", "Fri")
slots <- c("Coffee/Breakfast", "Lunch", "Happy Hour", "Dinner")

# Create the data frame
df <- expand.grid(days, slots)
df$value <- c(1, 1, 1, 1, 2, 1, 1, NA, NA, 1, 4, 4, 7, 4, 1, 5, 6, 14, 5, 1)

## Plot the data (my contribution)
ggballoonplot(
  data = df, 
  x = "Var1", 
  y = "Var2",
  size = "value",
  size.range = c(10, 20), 
  fill = "green",
  show.label = TRUE, 
  rotate.x.text = FALSE, 
  legend = "none"
)

reprex 包于 2021 年 6 月 12 日创建(v2.0.0)

© www.soinside.com 2019 - 2024. All rights reserved.