【问题标题】:Creating line graph using categorical data使用分类数据创建折线图
【发布时间】:2020-01-20 16:21:40
【问题描述】:

试图在检查年份显示“成绩”,而计数只是数据框中的观察值。

创建快速表:

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

创建快速条形图:

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

我想用折线图做同样的事情,但没有运气

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

有什么想法吗?

谢谢!

【问题讨论】:

  • geom_line 需要一个 y 参数。尝试更改折线图中 y 的填充。您可能必须改变数据框并在所需的 y 轴中包含另一列。

标签: r ggplot2


【解决方案1】:

假设您的数据如下所示:

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

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

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:

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

两者都给出了下面的情节:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-04-15
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多