首页 > 解决方案 > Ggplot2 和 tibble 绘制 geom_point 未检测到日期/因素

问题描述

我被这种奇怪的行为困住了,我可能没有注意到一些明显的事情。在数据争吵之后,我最终得到了一个长格式的数据集,就像 socviz 书中的那个:

在此处输入图像描述

但是在尝试生成条形图或 geom_points 时,ggplot 并未将年份视为单独的因素。请考虑这个 MWE:

dep <- function(x) {
  if(!all(x %in% installed.packages()))
    install.packages(x[x %in% installed.packages()[,"Package"] == F])
  lapply(x, require, character.only = T)
}
dep(c("dplyr", "tibble", "ggplot2"))

a<-tribble(
  ~region,  ~icd_group1,                                              ~year, ~visits,
  "Midwest", "F00-F09 Organic, Including Symptomatic, Mental Dis.",     2008,  2.59,
  "Midwest", "F10-F19 Mental And Behav. Dis. Due To Substance Use" ,    2008,  3.18, 
  "South", "F20-F29 Schizophrenia, Schizotypal And Delusional Dis.",  2009, 13.1,  
  "Southeast", "F30-F39 Mood [Affective] Dis.",                           2009, 26.7,  
  "Southeast", "F40-F48 Neurotic, Stress Related And Somatoform Dis.",    2010,  7.77, 
  "North", "F50-F59 Behav. Synd. Assoc. w/ Physical Factors",         2010,  0.409
)
ggplot(a) + geom_point(size = 3)+ aes(x = "year", y ="visits", color = icd_group1)

但我得到了这个:

在此处输入图像描述

我预计沿 x 轴的三年。

标签: rggplot2

解决方案


尝试这个:

library(tidyverse)
a %>% ggplot(aes(year, visits))+ geom_point(aes(color=icd_group1))

在此处输入图像描述


推荐阅读