简体   繁体   English

使用带有数字 x 轴的 ggplot 在 R 中绘制类别变量在 y 轴上的比例

[英]Plotting the proportion of a categorial variable on the y-axis in R using ggplot with a numerical x-axis

Here's some example data:以下是一些示例数据:

result  age
y   20
y   20
n   20
n   20
y   21
n   21
n   21
n   21
y   22
n   22
n   22

I would like to plot the proportion of " y " as a total of " result " on the y-axis against " age " on the x-axis, displayed as a line graph and preferably also with the dot representing the proportion / frequency of y ( geom_point ).我想 plot y轴上的“ result ”与 x 轴上的“ age ”的总比例为 plot y ( geom_point )。 I don't want to display " n ".我不想显示“ n ”。 Preferably using ggplot2 because I always use that.最好使用ggplot2因为我总是使用它。

Many thanks for any help非常感谢您的帮助

You can summarize the data with dplyr and then plot the summarized data frame rather than the original data frame您可以使用 dplyr 和 plot 汇总数据框而不是原始数据框

library(dplyr)
library(ggplot2)

df %>% 
  group_by(age) %>% 
  summarise(p = mean(result == 'y')) %>% 
  ggplot(aes(x = age, y = p)) +
    geom_point() + 
    geom_line()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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