使用分类数据创建折线图 [英] Creating line graph using categorical data

查看:39
本文介绍了使用分类数据创建折线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在检查年度显示等级",而计数只是数据框中的观察值.

Trying to display "Grades" over inspection year, and the count is just the observations in the data frame.

创建快速表格:

table(mydata1$Grade,mydata1$Inspection.Year)

创建快速条形图:

ggplot(mydata1, aes(fill=Grade , x=Inspection.Year)) +
  geom_bar()

我想对折线图做同样的事情,但运气不好

I want to do the same thing with a line graph, but no luck with

ggplot(mydata1, aes(fill=Grade , x=Inspection.Year)) +
  geom_line()

有什么想法吗?

谢谢!

推荐答案

假设您的数据看起来像这样:

Suppose your data looks something like this:

mydata1 = data.frame(
Inspection.Year=sample(2000:2005,100,replace=TRUE),
Grade=sample(LETTERS[1:3],10,replace=TRUE))

您需要统计计数并将它们绘制在y轴上,如下所示:

You need to tally your counts and plot them on the y-axis, so something like below:

library(dplyr)

mydata1 %>% count(Inspection.Year,Grade)
# A tibble: 17 x 3
   Inspection.Year Grade     n
             <int> <fct> <int>
 1            2000 A        11
 2            2000 B         6
 3            2000 C         1
 4            2001 A         8

并绘制此图:

mydata1 %>% count(Inspection.Year,Grade) %>%
ggplot()+geom_line(aes(x=Inspection.Year,y=n,col=Grade))

或者类似于geom_bar中的填充",您设置y = 1,然后使用stat_summary对每个年级/年总计1,这将为您提供n:

Or something similar to the "fill" in geom_bar, you set y=1, and use stat_summary to sum up the 1s per Grade / Year, which will give you n:

ggplot(mydata1, aes(col=Grade , x=Inspection.Year,y=1))+ stat_summary(geom="line",fun.y=sum)

两个都给出下面的图:

这篇关于使用分类数据创建折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆